@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,2973 @@
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
+ /* Date selector styling */
11
+ .controls-area {
12
+ display: flex;
13
+ align-items: center;
14
+ gap: 1rem;
15
+ background: var(--panel-bg);
16
+ border: 1px solid var(--panel-border);
17
+ padding: 0.5rem 1rem;
18
+ border-radius: 14px;
19
+ backdrop-filter: blur(12px);
20
+ }
21
+
22
+ .controls-area label {
23
+ font-size: 0.85rem;
24
+ font-weight: 600;
25
+ color: var(--text-muted);
26
+ text-transform: uppercase;
27
+ letter-spacing: 0.05em;
28
+ }
29
+
30
+ .select-custom, .select-native {
31
+ background: rgba(255, 255, 255, 0.05);
32
+ border: 1px solid var(--panel-border);
33
+ color: var(--text-main);
34
+ padding: 0.5rem 1.5rem 0.5rem 0.75rem;
35
+ border-radius: 8px;
36
+ font-family: var(--font-family);
37
+ font-weight: 500;
38
+ cursor: pointer;
39
+ outline: none;
40
+ transition: var(--transition-smooth);
41
+ appearance: none;
42
+ 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");
43
+ background-repeat: no-repeat;
44
+ background-position: right 8px center;
45
+ background-size: 16px;
46
+ }
47
+
48
+ .select-custom:focus, .select-native:focus {
49
+ border-color: var(--accent-primary);
50
+ box-shadow: 0 0 0 2px var(--accent-primary-glow);
51
+ }
52
+
53
+ /* KPI Grid */
54
+ .kpi-grid {
55
+ display: grid;
56
+ grid-template-columns: repeat(3, 1fr);
57
+ gap: 1.5rem;
58
+ }
59
+
60
+ @media (max-width: 900px) {
61
+ .kpi-grid {
62
+ grid-template-columns: repeat(2, 1fr);
63
+ }
64
+ }
65
+
66
+ @media (max-width: 600px) {
67
+ .kpi-grid {
68
+ grid-template-columns: 1fr;
69
+ }
70
+ }
71
+
72
+ /* base: ui/app.css (#164) */
73
+ .kpi-card {
74
+ align-items: center;
75
+ justify-content: space-between;
76
+ transition: var(--transition-smooth);
77
+ position: relative;
78
+ overflow: hidden;
79
+ }
80
+
81
+ .kpi-card::before {
82
+ background: transparent;
83
+ }
84
+
85
+ .kpi-card:hover {
86
+ transform: translateY(-5px);
87
+ border-color: rgba(255, 255, 255, 0.12);
88
+ }
89
+
90
+ .kpi-card.income::before { background: var(--income-color); }
91
+ .kpi-card.expense::before { background: var(--expense-color); }
92
+ .kpi-card.net::before { background: var(--accent-primary); }
93
+
94
+ .kpi-card.income:hover { box-shadow: 0 8px 30px rgba(16, 185, 129, 0.12); }
95
+ .kpi-card.expense:hover { box-shadow: 0 8px 30px rgba(244, 63, 94, 0.12); }
96
+ .kpi-card.net:hover { box-shadow: 0 8px 30px rgba(139, 92, 246, 0.12); }
97
+
98
+ .kpi-info h3 {
99
+ font-size: 0.85rem;
100
+ color: var(--text-muted);
101
+ text-transform: uppercase;
102
+ letter-spacing: 0.05em;
103
+ margin-bottom: 0.5rem;
104
+ }
105
+
106
+ .kpi-val {
107
+ font-size: 1.8rem;
108
+ font-weight: 700;
109
+ display: flex;
110
+ flex-direction: column;
111
+ gap: 0.25rem;
112
+ }
113
+
114
+ .kpi-val .secondary-val {
115
+ font-size: 1rem;
116
+ font-weight: 500;
117
+ color: var(--text-muted);
118
+ }
119
+
120
+ .kpi-card.income .kpi-val { color: var(--income-color); }
121
+ .kpi-card.expense .kpi-val { color: var(--expense-color); }
122
+
123
+ .kpi-icon {
124
+ width: 50px;
125
+ height: 50px;
126
+ border-radius: 12px;
127
+ display: flex;
128
+ align-items: center;
129
+ justify-content: center;
130
+ font-size: 1.3rem;
131
+ background: rgba(255, 255, 255, 0.03);
132
+ }
133
+
134
+ .kpi-card.income .kpi-icon { color: var(--income-color); background: rgba(16, 185, 129, 0.1); }
135
+ .kpi-card.expense .kpi-icon { color: var(--expense-color); background: rgba(244, 63, 94, 0.1); }
136
+ .kpi-card.net .kpi-icon { color: var(--accent-primary); background: rgba(139, 92, 246, 0.1); }
137
+
138
+ /* Dashboard Body Grid */
139
+ .main-grid {
140
+ display: grid;
141
+ grid-template-columns: minmax(0, 2.2fr) minmax(0, 1fr);
142
+ gap: 1.5rem;
143
+ }
144
+
145
+ @media (max-width: 1024px) {
146
+ .main-grid {
147
+ grid-template-columns: 1fr;
148
+ }
149
+ }
150
+
151
+ /* base: ui/app.css (#164) */
152
+ .panel {
153
+ padding: 1.5rem;
154
+ display: flex;
155
+ flex-direction: column;
156
+ gap: 1.5rem;
157
+ }
158
+
159
+ .panel-header {
160
+ display: flex;
161
+ justify-content: space-between;
162
+ align-items: center;
163
+ flex-wrap: wrap;
164
+ gap: 1rem;
165
+ }
166
+
167
+ .panel-title {
168
+ font-size: 1.25rem;
169
+ font-weight: 600;
170
+ display: flex;
171
+ align-items: center;
172
+ gap: 0.5rem;
173
+ }
174
+
175
+ .panel-title i {
176
+ color: var(--accent-primary);
177
+ }
178
+
179
+ /* Filter Controls */
180
+ .filter-row {
181
+ display: flex;
182
+ gap: 0.75rem;
183
+ flex-wrap: wrap;
184
+ width: 100%;
185
+ align-items: center;
186
+ }
187
+
188
+ .search-wrapper {
189
+ position: relative;
190
+ flex: 1;
191
+ min-width: 180px;
192
+ }
193
+
194
+ .search-wrapper i {
195
+ position: absolute;
196
+ left: 12px;
197
+ top: 50%;
198
+ transform: translateY(-50%);
199
+ color: var(--text-dark);
200
+ font-size: 0.9rem;
201
+ transition: var(--transition-smooth);
202
+ }
203
+
204
+ .search-input {
205
+ width: 100%;
206
+ box-sizing: border-box;
207
+ background: rgba(255, 255, 255, 0.04);
208
+ border: 1px solid var(--panel-border);
209
+ color: var(--text-main);
210
+ padding: 0.6rem 0.75rem 0.6rem 2.2rem;
211
+ border-radius: 10px;
212
+ font-family: var(--font-family);
213
+ outline: none;
214
+ transition: var(--transition-smooth);
215
+ }
216
+
217
+ .search-input:focus {
218
+ border-color: var(--accent-primary);
219
+ background: rgba(255, 255, 255, 0.08);
220
+ box-shadow: 0 0 0 2px var(--accent-primary-glow);
221
+ }
222
+
223
+ .search-input:focus + i {
224
+ color: var(--accent-primary);
225
+ }
226
+
227
+ .filter-wrapper {
228
+ flex: 0 0 115px;
229
+ min-width: 115px;
230
+ }
231
+
232
+ .filter-wrapper select {
233
+ width: 100%;
234
+ padding: 0.6rem 1.5rem 0.6rem 0.75rem;
235
+ border-radius: 10px;
236
+ }
237
+
238
+ .filter-wrapper .select-container-custom {
239
+ width: 100%;
240
+ }
241
+
242
+ /* Custom Multiselect Dropdowns styling */
243
+ .multiselect-container {
244
+ position: relative;
245
+ flex: 0 0 130px;
246
+ min-width: 130px;
247
+ }
248
+
249
+ @media (max-width: 580px) {
250
+ .search-wrapper, .filter-wrapper, .multiselect-container {
251
+ flex: 1 1 100%;
252
+ min-width: 100%;
253
+ }
254
+ }
255
+
256
+ .multiselect-btn {
257
+ width: 100%;
258
+ background: rgba(255, 255, 255, 0.05);
259
+ border: 1px solid var(--panel-border);
260
+ color: var(--text-main);
261
+ padding: 0.6rem 1rem;
262
+ border-radius: 10px;
263
+ font-family: var(--font-family);
264
+ font-weight: 500;
265
+ font-size: 0.9rem;
266
+ cursor: pointer;
267
+ display: flex;
268
+ justify-content: space-between;
269
+ align-items: center;
270
+ outline: none;
271
+ transition: var(--transition-smooth);
272
+ }
273
+
274
+ .multiselect-btn:focus {
275
+ border-color: var(--accent-primary);
276
+ box-shadow: 0 0 0 2px var(--accent-primary-glow);
277
+ }
278
+
279
+ .multiselect-dropdown {
280
+ position: absolute;
281
+ top: calc(100% + 8px);
282
+ left: 0;
283
+ width: 100%;
284
+ min-width: 270px;
285
+ background: rgba(15, 18, 33, 0.97);
286
+ border: 1px solid var(--panel-border);
287
+ border-radius: 12px;
288
+ padding: 0.75rem;
289
+ box-shadow: 0 10px 35px rgba(0, 0, 0, 0.6);
290
+ backdrop-filter: blur(20px);
291
+ z-index: 100;
292
+ display: none;
293
+ flex-direction: column;
294
+ gap: 0.5rem;
295
+ }
296
+
297
+ #account-multiselect .multiselect-dropdown {
298
+ right: 0;
299
+ left: auto;
300
+ }
301
+
302
+ .multiselect-container.open .multiselect-dropdown {
303
+ display: flex;
304
+ }
305
+
306
+ .multiselect-container.open .multiselect-btn i {
307
+ transform: rotate(180deg);
308
+ }
309
+
310
+ .multiselect-actions {
311
+ display: flex;
312
+ justify-content: space-between;
313
+ border-bottom: 1px solid rgba(255, 255, 255, 0.06);
314
+ padding-bottom: 0.5rem;
315
+ margin-bottom: 0.25rem;
316
+ }
317
+
318
+ .btn-link {
319
+ background: none;
320
+ border: none;
321
+ color: var(--accent-primary);
322
+ font-size: 0.75rem;
323
+ font-weight: 600;
324
+ cursor: pointer;
325
+ font-family: var(--font-family);
326
+ }
327
+
328
+ .btn-link:hover {
329
+ text-decoration: underline;
330
+ }
331
+
332
+ .multiselect-options {
333
+ overflow-y: auto;
334
+ max-height: 250px;
335
+ display: flex;
336
+ flex-direction: column;
337
+ gap: 0.35rem;
338
+ padding-right: 0.25rem;
339
+ }
340
+
341
+ .multiselect-options::-webkit-scrollbar {
342
+ width: 6px;
343
+ }
344
+ .multiselect-options::-webkit-scrollbar-thumb {
345
+ background: rgba(255, 255, 255, 0.1);
346
+ border-radius: 99px;
347
+ }
348
+
349
+ .multiselect-option {
350
+ display: flex;
351
+ align-items: center;
352
+ gap: 0.5rem;
353
+ font-size: 0.85rem;
354
+ color: var(--text-muted);
355
+ cursor: pointer;
356
+ padding: 0.25rem 0.5rem;
357
+ border-radius: 6px;
358
+ transition: var(--transition-smooth);
359
+ user-select: none;
360
+ }
361
+
362
+ .multiselect-option:hover {
363
+ background: rgba(255, 255, 255, 0.03);
364
+ color: var(--text-main);
365
+ }
366
+
367
+ .multiselect-option input[type="checkbox"] {
368
+ accent-color: var(--accent-primary);
369
+ cursor: pointer;
370
+ }
371
+
372
+ /* Table design */
373
+ .table-container {
374
+ overflow-x: auto;
375
+ position: relative;
376
+ border-radius: 14px;
377
+ border: 1px solid var(--panel-border);
378
+ background: rgba(0, 0, 0, 0.1);
379
+ }
380
+
381
+ table {
382
+ width: 100%;
383
+ border-collapse: collapse;
384
+ text-align: left;
385
+ font-size: 0.9rem;
386
+ }
387
+
388
+ th {
389
+ background: rgba(255, 255, 255, 0.02);
390
+ color: var(--text-muted);
391
+ font-weight: 600;
392
+ padding: 0.75rem 0.6rem;
393
+ border-bottom: 1px solid var(--panel-border);
394
+ text-transform: uppercase;
395
+ font-size: 0.75rem;
396
+ letter-spacing: 0.05em;
397
+ }
398
+
399
+ th.sortable {
400
+ cursor: pointer;
401
+ user-select: none;
402
+ transition: var(--transition-smooth);
403
+ }
404
+
405
+ th.sortable:hover {
406
+ color: var(--text-main);
407
+ background: rgba(255, 255, 255, 0.04);
408
+ }
409
+
410
+ th i {
411
+ margin-left: 0.35rem;
412
+ font-size: 0.8rem;
413
+ transition: var(--transition-smooth);
414
+ }
415
+
416
+ td {
417
+ padding: 0.75rem 0.6rem;
418
+ border-bottom: 1px solid rgba(255, 255, 255, 0.03);
419
+ vertical-align: middle;
420
+ color: var(--text-main);
421
+ }
422
+
423
+ tr {
424
+ transition: var(--transition-smooth);
425
+ }
426
+
427
+ tr:hover td {
428
+ background: rgba(255, 255, 255, 0.02);
429
+ }
430
+
431
+ tr:last-child td {
432
+ border-bottom: none;
433
+ }
434
+
435
+ /* Today highlight style */
436
+ tr.today-row td {
437
+ background: rgba(139, 92, 246, 0.1) !important;
438
+ }
439
+
440
+ tr.today-row td:first-child {
441
+ border-left: 4px solid var(--accent-primary);
442
+ }
443
+
444
+ /* Table specific styles */
445
+ .col-date {
446
+ color: var(--text-muted);
447
+ white-space: nowrap;
448
+ }
449
+
450
+ .col-desc {
451
+ font-weight: 500;
452
+ }
453
+
454
+ .col-category {
455
+ white-space: nowrap;
456
+ }
457
+
458
+ .badge-cat {
459
+ background: rgba(255, 255, 255, 0.04);
460
+ border: 1px solid var(--panel-border);
461
+ padding: 0.25rem 0.6rem;
462
+ border-radius: 6px;
463
+ font-size: 0.8rem;
464
+ color: var(--text-muted);
465
+ transition: var(--transition-smooth);
466
+ }
467
+
468
+ .badge-acc {
469
+ display: inline-flex;
470
+ align-items: center;
471
+ gap: 0.35rem;
472
+ font-size: 0.8rem;
473
+ color: var(--text-muted);
474
+ }
475
+
476
+ .badge-acc i {
477
+ font-size: 0.85rem;
478
+ opacity: 0.6;
479
+ }
480
+
481
+ .amount-cell {
482
+ font-weight: 700;
483
+ text-align: right;
484
+ white-space: nowrap;
485
+ }
486
+
487
+ .amount-cell.income { color: var(--income-color); }
488
+ .amount-cell.expense { color: var(--expense-color); }
489
+
490
+ /* Actions layout & flat buttons */
491
+ .actions-cell {
492
+ display: flex;
493
+ justify-content: center;
494
+ align-items: center;
495
+ gap: 0.75rem;
496
+ }
497
+
498
+ .action-btn {
499
+ background: transparent;
500
+ border: none;
501
+ cursor: pointer;
502
+ font-size: 1.05rem;
503
+ display: inline-flex;
504
+ align-items: center;
505
+ justify-content: center;
506
+ width: 28px;
507
+ height: 28px;
508
+ border-radius: 6px;
509
+ transition: var(--transition-smooth);
510
+ }
511
+
512
+ .btn-confirm-icon {
513
+ color: var(--income-color);
514
+ opacity: 0.65;
515
+ }
516
+
517
+ .btn-confirm-icon:hover {
518
+ opacity: 1;
519
+ transform: scale(1.25);
520
+ }
521
+
522
+ .btn-delete-icon {
523
+ color: var(--expense-color);
524
+ opacity: 0.65;
525
+ }
526
+
527
+ .btn-delete-icon:hover {
528
+ opacity: 1;
529
+ transform: scale(1.25);
530
+ }
531
+
532
+ /* Charts panel */
533
+ .charts-panel {
534
+ display: flex;
535
+ flex-direction: column;
536
+ gap: 2rem;
537
+ }
538
+
539
+ .chart-box {
540
+ background: rgba(0, 0, 0, 0.15);
541
+ border: 1px solid var(--panel-border);
542
+ border-radius: 18px;
543
+ padding: 1.25rem;
544
+ display: flex;
545
+ flex-direction: column;
546
+ align-items: center;
547
+ justify-content: center;
548
+ position: relative;
549
+ min-height: 250px;
550
+ }
551
+
552
+ .chart-box-title {
553
+ align-self: flex-start;
554
+ font-size: 0.9rem;
555
+ font-weight: 600;
556
+ color: var(--text-muted);
557
+ margin-bottom: 1rem;
558
+ display: flex;
559
+ align-items: center;
560
+ gap: 0.35rem;
561
+ }
562
+
563
+ /* Toast system (.toast-container/.toast base: ui/app.css, #164) */
564
+ .toast-container {
565
+ z-index: 1000;
566
+ }
567
+
568
+ .toast {
569
+ color: var(--text-main);
570
+ border-left: 4px solid var(--accent-primary);
571
+ backdrop-filter: blur(12px);
572
+ min-width: 300px;
573
+ animation: slideIn 0.35s cubic-bezier(0.175, 0.885, 0.32, 1.275) forwards;
574
+ position: relative;
575
+ }
576
+
577
+ .toast.success { border-left-color: var(--income-color); }
578
+ .toast.error { border-left-color: var(--expense-color); }
579
+
580
+ .toast-close {
581
+ position: absolute;
582
+ right: 10px;
583
+ top: 50%;
584
+ transform: translateY(-50%);
585
+ color: var(--text-dark);
586
+ cursor: pointer;
587
+ font-size: 0.8rem;
588
+ }
589
+
590
+ .toast-close:hover {
591
+ color: var(--text-main);
592
+ }
593
+
594
+ @keyframes slideIn {
595
+ from {
596
+ transform: translateX(100%);
597
+ opacity: 0;
598
+ }
599
+ to {
600
+ transform: translateX(0);
601
+ opacity: 1;
602
+ }
603
+ }
604
+
605
+ @keyframes fadeOut {
606
+ to {
607
+ opacity: 0;
608
+ transform: translateY(20px);
609
+ }
610
+ }
611
+
612
+ /* Loading / Empty States (.loading-overlay/.spinner base: ui/app.css, #164) */
613
+ .loading-overlay {
614
+ width: 100%;
615
+ height: 100%;
616
+ border-radius: 24px;
617
+ opacity: 0;
618
+ pointer-events: none;
619
+ transition: opacity 0.25s ease;
620
+ }
621
+
622
+ .loading-overlay.active {
623
+ opacity: 1;
624
+ pointer-events: all;
625
+ }
626
+
627
+ .no-data-msg {
628
+ text-align: center;
629
+ padding: 3rem;
630
+ color: var(--text-dark);
631
+ font-weight: 500;
632
+ }
633
+
634
+ .no-data-msg i {
635
+ font-size: 2.5rem;
636
+ margin-bottom: 0.75rem;
637
+ display: block;
638
+ opacity: 0.5;
639
+ }
640
+
641
+ /* Pagination & Stats */
642
+ .table-footer {
643
+ display: flex;
644
+ justify-content: space-between;
645
+ align-items: center;
646
+ padding: 1rem;
647
+ border-top: 1px solid var(--panel-border);
648
+ flex-wrap: wrap;
649
+ gap: 1rem;
650
+ }
651
+
652
+ .pagination-info {
653
+ font-size: 0.8rem;
654
+ color: var(--text-muted);
655
+ }
656
+
657
+ .pagination-buttons {
658
+ display: flex;
659
+ gap: 0.5rem;
660
+ }
661
+
662
+ .btn-page {
663
+ background: rgba(255, 255, 255, 0.04);
664
+ border: 1px solid var(--panel-border);
665
+ color: var(--text-main);
666
+ padding: 0.35rem 0.75rem;
667
+ border-radius: 6px;
668
+ font-size: 0.8rem;
669
+ cursor: pointer;
670
+ transition: var(--transition-smooth);
671
+ }
672
+
673
+ .btn-page:hover:not(:disabled) {
674
+ background: rgba(255, 255, 255, 0.1);
675
+ border-color: rgba(255, 255, 255, 0.2);
676
+ }
677
+
678
+ .btn-page:disabled {
679
+ opacity: 0.4;
680
+ cursor: not-allowed;
681
+ }
682
+
683
+ /* Custom Select component styling */
684
+ .select-container-custom {
685
+ position: relative;
686
+ display: inline-block;
687
+ min-width: 120px;
688
+ user-select: none;
689
+ }
690
+
691
+ .select-trigger-custom {
692
+ background: rgba(255, 255, 255, 0.05);
693
+ border: 1px solid var(--panel-border);
694
+ color: var(--text-main);
695
+ padding: 0.5rem 2.2rem 0.5rem 0.75rem;
696
+ border-radius: 8px;
697
+ cursor: pointer;
698
+ font-size: 0.85rem;
699
+ font-weight: 600;
700
+ display: flex;
701
+ align-items: center;
702
+ justify-content: space-between;
703
+ transition: var(--transition-smooth);
704
+ min-height: 36px;
705
+ box-sizing: border-box;
706
+ }
707
+
708
+ .select-trigger-custom:hover {
709
+ border-color: rgba(255, 255, 255, 0.15);
710
+ background: rgba(255, 255, 255, 0.08);
711
+ }
712
+
713
+ .select-container-custom.open .select-trigger-custom {
714
+ border-color: var(--accent-primary);
715
+ box-shadow: 0 0 0 2px var(--accent-primary-glow);
716
+ }
717
+
718
+ .select-trigger-custom::after {
719
+ content: '\f078';
720
+ font-family: 'Font Awesome 6 Free';
721
+ font-weight: 900;
722
+ font-size: 0.7rem;
723
+ color: var(--text-muted);
724
+ position: absolute;
725
+ right: 12px;
726
+ transition: transform 0.3s ease;
727
+ }
728
+
729
+ .select-container-custom.open .select-trigger-custom::after {
730
+ transform: rotate(180deg);
731
+ color: var(--accent-primary);
732
+ }
733
+
734
+ .select-options-custom {
735
+ display: none;
736
+ position: absolute;
737
+ top: calc(100% + 6px);
738
+ left: 0;
739
+ width: 100%;
740
+ background: rgba(22, 22, 34, 0.98); /* Opaque dark background to prevent bleed-through */
741
+ border: 1px solid var(--panel-border);
742
+ border-radius: 12px;
743
+ box-shadow: 0 10px 25px rgba(0, 0, 0, 0.6);
744
+ z-index: 1000;
745
+ max-height: 250px;
746
+ overflow-y: auto;
747
+ padding: 4px;
748
+ backdrop-filter: blur(20px);
749
+ box-sizing: border-box;
750
+ animation: selectFadeIn 0.2s cubic-bezier(0.16, 1, 0.3, 1);
751
+ }
752
+
753
+ @keyframes selectFadeIn {
754
+ from { opacity: 0; transform: translateY(-8px); }
755
+ to { opacity: 1; transform: translateY(0); }
756
+ }
757
+
758
+ .select-container-custom.open .select-options-custom {
759
+ display: block;
760
+ }
761
+
762
+ .select-option-custom {
763
+ padding: 0.5rem 0.75rem;
764
+ color: var(--text-muted); /* Highly readable text color on dark backgrounds */
765
+ font-size: 0.82rem;
766
+ font-weight: 500;
767
+ border-radius: 6px;
768
+ cursor: pointer;
769
+ transition: var(--transition-smooth);
770
+ }
771
+
772
+ .select-option-custom:hover {
773
+ background: rgba(255, 255, 255, 0.08);
774
+ color: #fff;
775
+ }
776
+
777
+ .select-option-custom.selected {
778
+ background: var(--accent-primary-glow);
779
+ color: var(--accent-primary);
780
+ font-weight: 700;
781
+ }
782
+
783
+ .select-options-custom::-webkit-scrollbar {
784
+ width: 6px;
785
+ }
786
+ .select-options-custom::-webkit-scrollbar-track {
787
+ background: transparent;
788
+ }
789
+ .select-options-custom::-webkit-scrollbar-thumb {
790
+ background: rgba(255, 255, 255, 0.1);
791
+ border-radius: 3px;
792
+ }
793
+
794
+ /* Modal Dialog styling (.modal-overlay/.modal-box/.modal-title base: ui/app.css, #164) */
795
+ .modal-overlay {
796
+ width: 100%; height: 100%;
797
+ }
798
+ .modal-overlay.open {
799
+ display: flex;
800
+ }
801
+
802
+ .modal-close-btn {
803
+ position: absolute;
804
+ top: 1.25rem;
805
+ right: 1.25rem;
806
+ background: none;
807
+ border: none;
808
+ color: var(--text-dark);
809
+ cursor: pointer;
810
+ font-size: 1.2rem;
811
+ transition: var(--transition-smooth);
812
+ }
813
+ .modal-close-btn:hover {
814
+ color: var(--text-main);
815
+ }
816
+
817
+ .modal-title {
818
+ margin-bottom: 1.5rem;
819
+ color: #fff;
820
+ }
821
+
822
+ .form-group {
823
+ margin-bottom: 1.25rem;
824
+ display: flex;
825
+ flex-direction: column;
826
+ gap: 0.5rem;
827
+ }
828
+
829
+ /* .form-group label / .form-control base: ui/app.css (#164) */
830
+ .form-control {
831
+ outline: none;
832
+ box-sizing: border-box;
833
+ }
834
+
835
+ /* Dark datepicker input custom style overrides */
836
+ input[type="date"] {
837
+ color-scheme: dark;
838
+ }
839
+ input[type="date"]::-webkit-calendar-picker-indicator {
840
+ filter: invert(0.9) sepia(1) saturate(5) hue-rotate(240deg);
841
+ cursor: pointer;
842
+ }
843
+
844
+ /* Custom Flatpickr styling overrides to match theme */
845
+ .flatpickr-calendar {
846
+ background: #111322 !important;
847
+ border: 1px solid var(--panel-border) !important;
848
+ box-shadow: 0 10px 25px rgba(0,0,0,0.6) !important;
849
+ font-family: var(--font-family) !important;
850
+ border-radius: 12px !important;
851
+ }
852
+ .flatpickr-day.selected,
853
+ .flatpickr-day.startRange,
854
+ .flatpickr-day.endRange,
855
+ .flatpickr-day.selected.inRange,
856
+ .flatpickr-day.startRange.inRange,
857
+ .flatpickr-day.endRange.inRange,
858
+ .flatpickr-day.selected:focus,
859
+ .flatpickr-day.startRange:focus,
860
+ .flatpickr-day.endRange:focus,
861
+ .flatpickr-day.selected:hover,
862
+ .flatpickr-day.startRange:hover,
863
+ .flatpickr-day.endRange:hover,
864
+ .flatpickr-day.prevMonthDay.selected,
865
+ .flatpickr-day.nextMonthDay.selected {
866
+ background: var(--accent-primary) !important;
867
+ border-color: var(--accent-primary) !important;
868
+ }
869
+ .flatpickr-months .flatpickr-month {
870
+ color: #fff !important;
871
+ }
872
+ .flatpickr-current-month .flatpickr-monthDropdown-months {
873
+ background: #111322 !important;
874
+ color: #fff !important;
875
+ }
876
+ .flatpickr-day {
877
+ color: var(--text-main) !important;
878
+ }
879
+ .flatpickr-day:hover {
880
+ background: rgba(255, 255, 255, 0.08) !important;
881
+ }
882
+ .flatpickr-day.flatpickr-disabled,
883
+ .flatpickr-day.flatpickr-disabled:hover {
884
+ color: var(--text-dark) !important;
885
+ background: transparent !important;
886
+ }
887
+ .flatpickr-weekday {
888
+ color: var(--text-muted) !important;
889
+ }
890
+ .flatpickr-months .flatpickr-prev-month, .flatpickr-months .flatpickr-next-month {
891
+ color: var(--text-muted) !important;
892
+ fill: var(--text-muted) !important;
893
+ }
894
+ .flatpickr-calendar.arrowTop:before, .flatpickr-calendar.arrowTop:after {
895
+ border-bottom-color: #111322 !important;
896
+ }
897
+ .flatpickr-calendar.arrowBottom:before, .flatpickr-calendar.arrowBottom:after {
898
+ border-top-color: #111322 !important;
899
+ }
900
+
901
+ /* base: ui/app.css (#164) */
902
+ .btn-action-primary {
903
+ width: 100%;
904
+ padding: 0.75rem;
905
+ border-radius: 12px;
906
+ font-family: var(--font-family);
907
+ display: flex;
908
+ justify-content: center;
909
+ box-shadow: 0 4px 15px var(--accent-primary-glow);
910
+ }
911
+
912
+ .btn-action-primary:hover:not(:disabled) {
913
+ transform: translateY(-2px);
914
+ background: #9d76fd;
915
+ box-shadow: 0 6px 20px rgba(139, 92, 246, 0.55);
916
+ }
917
+
918
+ .btn-action-primary:disabled {
919
+ opacity: 0.5;
920
+ cursor: not-allowed;
921
+ box-shadow: none;
922
+ }
923
+
924
+ .btn-action-secondary {
925
+ width: 100%;
926
+ background: rgba(255,255,255,0.04);
927
+ border: 1px solid var(--panel-border);
928
+ color: var(--text-main);
929
+ padding: 0.75rem;
930
+ border-radius: 12px;
931
+ font-family: var(--font-family);
932
+ font-weight: 600;
933
+ cursor: pointer;
934
+ transition: var(--transition-smooth);
935
+ display: flex;
936
+ justify-content: center;
937
+ align-items: center;
938
+ gap: 0.5rem;
939
+ }
940
+
941
+ .btn-action-secondary:hover:not(:disabled) {
942
+ background: rgba(255,255,255,0.08);
943
+ border-color: rgba(255,255,255,0.15);
944
+ transform: translateY(-2px);
945
+ }
946
+
947
+ .modal-footer {
948
+ display: flex;
949
+ justify-content: flex-end;
950
+ gap: 0.75rem;
951
+ margin-top: 1.5rem;
952
+ }
953
+ </style>
954
+
955
+ <div class="dashboard-container">
956
+ <!-- Header -->
957
+ <header>
958
+ <div class="header-title-area">
959
+ <h1><i class="fa-solid fa-clock-rotate-left"></i> Transações Pendentes</h1>
960
+ <p>Monitore, analise e confirme seus lançamentos previstos e recorrentes</p>
961
+ </div>
962
+ <div class="controls-area">
963
+ <label for="month-select" data-i18n="reference_label">Reference:</label>
964
+ <select id="month-select" class="select-custom">
965
+ <option value="1">Janeiro</option>
966
+ <option value="2">Fevereiro</option>
967
+ <option value="3">Março</option>
968
+ <option value="4">Abril</option>
969
+ <option value="5">Maio</option>
970
+ <option value="6">Junho</option>
971
+ <option value="7" selected>Julho</option>
972
+ <option value="8">Agosto</option>
973
+ <option value="9">Setembro</option>
974
+ <option value="10">Outubro</option>
975
+ <option value="11">Novembro</option>
976
+ <option value="12">Dezembro</option>
977
+ </select>
978
+ <select id="year-select" class="select-custom">
979
+ <option value="2025">2025</option>
980
+ <option value="2026" selected>2026</option>
981
+ <option value="2027">2027</option>
982
+ </select>
983
+ </div>
984
+ </header>
985
+
986
+ <!-- KPI Grid -->
987
+ <section class="kpi-grid">
988
+ <div class="kpi-card income">
989
+ <div class="kpi-info">
990
+ <h3>Receitas Previstas</h3>
991
+ <div class="kpi-val" id="kpi-total-income">
992
+ <span>—</span>
993
+ </div>
994
+ </div>
995
+ <div class="kpi-icon"><i class="fa-solid fa-arrow-trend-up"></i></div>
996
+ </div>
997
+ <div class="kpi-card expense">
998
+ <div class="kpi-info">
999
+ <h3>Despesas Previstas</h3>
1000
+ <div class="kpi-val" id="kpi-total-expense">
1001
+ <span>—</span>
1002
+ </div>
1003
+ </div>
1004
+ <div class="kpi-icon"><i class="fa-solid fa-arrow-trend-down"></i></div>
1005
+ </div>
1006
+ <div class="kpi-card net">
1007
+ <div class="kpi-info">
1008
+ <h3>Saldo Líquido Previsto</h3>
1009
+ <div class="kpi-val" id="kpi-net-balance">
1010
+ <span>—</span>
1011
+ </div>
1012
+ </div>
1013
+ <div class="kpi-icon"><i class="fa-solid fa-scale-balanced"></i></div>
1014
+ </div>
1015
+ </section>
1016
+
1017
+ <!-- Main Body Grid -->
1018
+ <div class="main-grid">
1019
+ <!-- Left Panel: Table of transactions -->
1020
+ <section class="panel" style="position: relative;">
1021
+ <div class="loading-overlay" id="table-loading">
1022
+ <div class="spinner"></div>
1023
+ </div>
1024
+
1025
+ <div class="panel-header">
1026
+ <div class="panel-title">
1027
+ <i class="fa-solid fa-list-check"></i>
1028
+ <span>Lista de Lançamentos Pendentes</span>
1029
+ </div>
1030
+ </div>
1031
+
1032
+ <!-- Filter Controls -->
1033
+ <div class="filter-row">
1034
+ <div class="search-wrapper">
1035
+ <input type="text" id="search-text" class="search-input" placeholder="Pesquisar por descrição ou tag...">
1036
+ <i class="fa-solid fa-magnifying-glass"></i>
1037
+ </div>
1038
+ <div class="filter-wrapper">
1039
+ <select id="filter-type" class="select-custom" style="width: 100%;">
1040
+ <option value="">Ambos</option>
1041
+ <option value="expense">Despesas</option>
1042
+ <option value="income">Receitas</option>
1043
+ </select>
1044
+ </div>
1045
+
1046
+ <!-- Category Multiselect -->
1047
+ <div class="multiselect-container" id="category-multiselect">
1048
+ <button class="multiselect-btn" type="button">
1049
+ <span class="multiselect-label">Categorias</span>
1050
+ <i class="fa-solid fa-chevron-down"></i>
1051
+ </button>
1052
+ <div class="multiselect-dropdown">
1053
+ <div class="multiselect-actions">
1054
+ <button type="button" class="btn-link select-all">Todas</button>
1055
+ <button type="button" class="btn-link clear-all">Nenhuma</button>
1056
+ </div>
1057
+ <div class="multiselect-options" id="category-multiselect-options">
1058
+ <!-- Populated dynamically -->
1059
+ </div>
1060
+ </div>
1061
+ </div>
1062
+
1063
+ <!-- Account Multiselect -->
1064
+ <div class="multiselect-container" id="account-multiselect">
1065
+ <button class="multiselect-btn" type="button">
1066
+ <span class="multiselect-label">Contas</span>
1067
+ <i class="fa-solid fa-chevron-down"></i>
1068
+ </button>
1069
+ <div class="multiselect-dropdown">
1070
+ <div class="multiselect-actions">
1071
+ <button type="button" class="btn-link select-all">Todas</button>
1072
+ <button type="button" class="btn-link clear-all">Nenhuma</button>
1073
+ </div>
1074
+ <div class="multiselect-options" id="account-multiselect-options">
1075
+ <!-- Populated dynamically -->
1076
+ </div>
1077
+ </div>
1078
+ </div>
1079
+ </div>
1080
+
1081
+ <!-- Table -->
1082
+ <div class="table-container">
1083
+ <table id="transactions-table">
1084
+ <thead>
1085
+ <tr>
1086
+ <th class="sortable" onclick="toggleSort('date')">Data <i class="fa-solid fa-sort" id="sort-icon-date"></i></th>
1087
+ <th class="sortable" onclick="toggleSort('type')" style="text-align: center; width: 70px;">Tipo <i class="fa-solid fa-sort" id="sort-icon-type"></i></th>
1088
+ <th class="sortable" onclick="toggleSort('description')">Descrição <i class="fa-solid fa-sort" id="sort-icon-description"></i></th>
1089
+ <th class="sortable" onclick="toggleSort('category')">Categoria <i class="fa-solid fa-sort" id="sort-icon-category"></i></th>
1090
+ <th class="sortable" onclick="toggleSort('account')">Conta / Cartão <i class="fa-solid fa-sort" id="sort-icon-account"></i></th>
1091
+ <th class="sortable" onclick="toggleSort('amount')" style="text-align: right;">Valor <i class="fa-solid fa-sort" id="sort-icon-amount"></i></th>
1092
+ <th style="text-align: center;">Ações</th>
1093
+ </tr>
1094
+ </thead>
1095
+ <tbody id="table-body">
1096
+ <!-- Populated dynamically -->
1097
+ </tbody>
1098
+ </table>
1099
+ <div id="no-data" class="no-data-msg" style="display: none;">
1100
+ <i class="fa-regular fa-folder-open"></i>
1101
+ Nenhuma transação pendente encontrada para os filtros selecionados.
1102
+ </div>
1103
+ </div>
1104
+
1105
+ <!-- Footer Pagination -->
1106
+ <div class="table-footer">
1107
+ <div class="pagination-info" id="pagination-text">
1108
+ Exibindo 0 de 0 transações
1109
+ </div>
1110
+ <div class="pagination-buttons">
1111
+ <button class="btn-page" id="btn-prev" disabled><i class="fa-solid fa-chevron-left"></i> Anterior</button>
1112
+ <button class="btn-page" id="btn-next" disabled>Próxima <i class="fa-solid fa-chevron-right"></i></button>
1113
+ </div>
1114
+ </div>
1115
+ </section>
1116
+
1117
+ <!-- Right Panel: Analytics/Charts -->
1118
+ <section class="charts-panel">
1119
+ <div class="controls-group" id="chart-currency-group" style="display:none;">
1120
+ <label for="chart-currency-select" data-i18n="pending_chart_currency_label">Moeda:</label>
1121
+ <select id="chart-currency-select" class="select-native"></select>
1122
+ </div>
1123
+ <div class="panel">
1124
+ <div class="panel-header">
1125
+ <div class="panel-title">
1126
+ <i class="fa-solid fa-chart-pie"></i>
1127
+ <span id="chart-title-category" data-i18n="pending_chart_by_category">Despesas por Categoria</span>
1128
+ </div>
1129
+ </div>
1130
+ <div class="chart-box">
1131
+ <canvas id="categoryChart"></canvas>
1132
+ </div>
1133
+ </div>
1134
+
1135
+ <div class="panel">
1136
+ <div class="panel-header">
1137
+ <div class="panel-title">
1138
+ <i class="fa-solid fa-chart-bar"></i>
1139
+ <span id="chart-title-top" data-i18n="pending_chart_top_expenses">Maiores Despesas Previstas</span>
1140
+ </div>
1141
+ </div>
1142
+ <div class="chart-box">
1143
+ <canvas id="topExpensesChart"></canvas>
1144
+ </div>
1145
+ </div>
1146
+ </section>
1147
+ </div>
1148
+ </div>
1149
+
1150
+ <!-- MODAL: CONFIRM TRANSACTION -->
1151
+ <div class="modal-overlay" id="modal-confirm-tx">
1152
+ <div class="modal-box">
1153
+ <button class="modal-close-btn" onclick="closeModal('modal-confirm-tx')"><i class="fa-solid fa-xmark"></i></button>
1154
+ <div class="modal-title">
1155
+ <i class="fa-solid fa-circle-check" style="color: var(--income-color);"></i>
1156
+ <span data-i18n="modal_confirm_tx_title">Confirmar Lançamento</span>
1157
+ </div>
1158
+ <form id="form-confirm-tx" onsubmit="handleConfirmSubmit(event)">
1159
+ <input type="hidden" id="confirm-tx-id">
1160
+ <div class="form-group">
1161
+ <label data-i18n="label_description">Lançamento</label>
1162
+ <div id="confirm-tx-desc" style="font-weight:600; font-size:1.1rem; color:#fff;">-</div>
1163
+ </div>
1164
+ <div class="form-group">
1165
+ <label for="confirm-tx-date" data-i18n="label_confirm_date">Data da Confirmação</label>
1166
+ <input type="date" id="confirm-tx-date" class="form-control" required>
1167
+ </div>
1168
+ <div class="form-group">
1169
+ <label for="confirm-tx-amount" data-i18n="label_value">Valor</label>
1170
+ <input type="number" id="confirm-tx-amount" step="0.01" min="0.01" class="form-control" required>
1171
+ </div>
1172
+ <div class="modal-footer">
1173
+ <button type="button" class="btn-action-secondary" onclick="closeModal('modal-confirm-tx')" style="width:auto;" data-i18n="btn_cancel">Cancelar</button>
1174
+ <button type="submit" class="btn-action-primary" style="width:auto;" data-i18n="btn_confirm">Confirmar</button>
1175
+ </div>
1176
+ </form>
1177
+ </div>
1178
+ </div>
1179
+
1180
+ <!-- Toast Notifications Container -->
1181
+ <div class="toast-container" id="toast-box"></div>
1182
+
1183
+
1184
+
1185
+ <script>
1186
+ // State management
1187
+ var allTransactions = [];
1188
+ var filteredTransactions = [];
1189
+ var currentPage = 1;
1190
+ var itemsPerPage = 12;
1191
+
1192
+ // Custom filter states
1193
+ var selectedCategories = new Set();
1194
+ var selectedAccounts = new Set();
1195
+ var totalCategoriesCount = 0;
1196
+ var totalAccountsCount = 0;
1197
+
1198
+ // Sorting state
1199
+ var sortColumn = 'date';
1200
+ var sortDirection = 'asc';
1201
+
1202
+ // Vibrant colors for expenses (released blue, cyan and indigo here to be mapped to the charts)
1203
+ var vibrantColors = [
1204
+ { hex: '#8b5cf6', bg: 'rgba(139, 92, 246, 0.1)', border: 'rgba(139, 92, 246, 0.25)', text: '#c084fc' }, // Purple
1205
+ { hex: '#3b82f6', bg: 'rgba(59, 130, 246, 0.1)', border: 'rgba(59, 130, 246, 0.25)', text: '#93c5fd' }, // Blue
1206
+ { hex: '#ec4899', bg: 'rgba(236, 72, 153, 0.1)', border: 'rgba(236, 72, 153, 0.25)', text: '#f9a8d4' }, // Pink
1207
+ { hex: '#f43f5e', bg: 'rgba(244, 63, 94, 0.1)', border: 'rgba(244, 63, 94, 0.25)', text: '#fda4af' }, // Rose
1208
+ { hex: '#06b6d4', bg: 'rgba(6, 182, 212, 0.1)', border: 'rgba(6, 182, 212, 0.25)', text: '#67e8f9' }, // Cyan
1209
+ { hex: '#f59e0b', bg: 'rgba(245, 158, 11, 0.1)', border: 'rgba(245, 158, 11, 0.25)', text: '#fcd34d' }, // Amber
1210
+ { hex: '#f97316', bg: 'rgba(249, 115, 22, 0.1)', border: 'rgba(249, 115, 22, 0.25)', text: '#fdba74' }, // Orange
1211
+ { hex: '#a855f7', bg: 'rgba(168, 85, 247, 0.1)', border: 'rgba(168, 85, 247, 0.25)', text: '#d8b4fe' }, // Violet
1212
+ { hex: '#6366f1', bg: 'rgba(99, 102, 241, 0.1)', border: 'rgba(99, 102, 241, 0.25)', text: '#a5b4fc' } // Indigo
1213
+ ];
1214
+
1215
+ // Specific pure green tones for income categories
1216
+ var incomeColors = [
1217
+ { hex: '#10b981', bg: 'rgba(16, 185, 129, 0.1)', border: 'rgba(16, 185, 129, 0.25)', text: '#6ee7b7' }, // Emerald
1218
+ { hex: '#14b8a6', bg: 'rgba(20, 184, 166, 0.1)', border: 'rgba(20, 184, 166, 0.25)', text: '#5eead4' }, // Teal
1219
+ { hex: '#22c55e', bg: 'rgba(34, 197, 94, 0.1)', border: 'rgba(34, 197, 94, 0.25)', text: '#86efac' }, // Green
1220
+ { hex: '#059669', bg: 'rgba(5, 150, 105, 0.1)', border: 'rgba(5, 150, 105, 0.25)', text: '#a7f3d0' } // Jade
1221
+ ];
1222
+
1223
+ var categoryColors = {};
1224
+ var expenseColorCounter = 0;
1225
+ var incomeColorCounter = 0;
1226
+
1227
+ function getCategoryColor(catName, type = 'expense') {
1228
+ const normalized = catName || 'Sem Categoria';
1229
+ const cacheKey = `${type}_${normalized}`;
1230
+ if (!categoryColors[cacheKey]) {
1231
+ if (type === 'income') {
1232
+ categoryColors[cacheKey] = incomeColors[incomeColorCounter % incomeColors.length];
1233
+ incomeColorCounter++;
1234
+ } else {
1235
+ categoryColors[cacheKey] = vibrantColors[expenseColorCounter % vibrantColors.length];
1236
+ expenseColorCounter++;
1237
+ }
1238
+ }
1239
+ return categoryColors[cacheKey];
1240
+ }
1241
+
1242
+ // Primary currency of the loaded period (KPI first line, chart default) and the currency
1243
+ // the charts currently show; a chart never mixes currencies.
1244
+ var primary = window.DEFAULT_CURRENCY;
1245
+ var chartCurrency = window.DEFAULT_CURRENCY;
1246
+ var chartCurrencyChosen = false;
1247
+
1248
+ // Chart instances
1249
+ var catChartInstance = null;
1250
+ var topExpChartInstance = null;
1251
+
1252
+ // Elements
1253
+ var monthSelect = document.getElementById('month-select');
1254
+ var yearSelect = document.getElementById('year-select');
1255
+ var searchInput = document.getElementById('search-text');
1256
+ var filterType = document.getElementById('filter-type');
1257
+ var tableBody = document.getElementById('table-body');
1258
+ var noDataMsg = document.getElementById('no-data');
1259
+ var paginationText = document.getElementById('pagination-text');
1260
+ var btnPrev = document.getElementById('btn-prev');
1261
+ var btnNext = document.getElementById('btn-next');
1262
+ var tableLoading = document.getElementById('table-loading');
1263
+
1264
+ // Initialize today's month/year
1265
+ var today = new Date();
1266
+ var now = new Date();
1267
+ var params = new URLSearchParams(window.location.search);
1268
+ var defaultMonth = parseInt(params.get('month')) || (now.getMonth() + 1);
1269
+ var defaultYear = parseInt(params.get('year')) || now.getFullYear();
1270
+ monthSelect.value = String(defaultMonth);
1271
+ yearSelect.value = String(defaultYear);
1272
+
1273
+ // Toast helper
1274
+ function showToast(message, type = 'info') {
1275
+ const toastBox = document.getElementById('toast-box');
1276
+ const toast = document.createElement('div');
1277
+ toast.className = `toast ${type}`;
1278
+
1279
+ let iconClass = 'fa-circle-info';
1280
+ if (type === 'success') iconClass = 'fa-circle-check';
1281
+ if (type === 'error') iconClass = 'fa-circle-exclamation';
1282
+
1283
+ toast.innerHTML = `
1284
+ <i class="fa-solid ${iconClass}"></i>
1285
+ <span>${escapeHtml(message)}</span>
1286
+ <i class="fa-solid fa-xmark toast-close"></i>
1287
+ `;
1288
+
1289
+ // Close event
1290
+ toast.querySelector('.toast-close').addEventListener('click', () => {
1291
+ toast.style.animation = 'fadeOut 0.3s forwards';
1292
+ setTimeout(() => toast.remove(), 300);
1293
+ });
1294
+
1295
+ toastBox.appendChild(toast);
1296
+
1297
+ // Auto dismiss
1298
+ setTimeout(() => {
1299
+ if (toast.parentNode) {
1300
+ toast.style.animation = 'fadeOut 0.3s forwards';
1301
+ setTimeout(() => toast.remove(), 300);
1302
+ }
1303
+ }, 4000);
1304
+ }
1305
+
1306
+ // Toggle Custom Multiselect Dropdowns
1307
+ function setupMultiselectToggles() {
1308
+ document.querySelectorAll('.multiselect-container').forEach(container => {
1309
+ const btn = container.querySelector('.multiselect-btn');
1310
+ btn.addEventListener('click', (e) => {
1311
+ e.stopPropagation();
1312
+ // Close others
1313
+ document.querySelectorAll('.multiselect-container').forEach(c => {
1314
+ if (c !== container) c.classList.remove('open');
1315
+ });
1316
+ container.classList.toggle('open');
1317
+ });
1318
+ });
1319
+
1320
+ // Close when clicking outside
1321
+ document.addEventListener('click', (e) => {
1322
+ document.querySelectorAll('.multiselect-container').forEach(c => {
1323
+ if (!c.contains(e.target)) {
1324
+ c.classList.remove('open');
1325
+ }
1326
+ });
1327
+ });
1328
+ }
1329
+
1330
+ // Update Multiselect Button Label
1331
+ function updateMultiselectButton(dropdownId, count, total) {
1332
+ const container = document.getElementById(dropdownId);
1333
+ const label = container.querySelector('.multiselect-label');
1334
+ const name = dropdownId === 'category-multiselect' ? 'Categoria' : 'Conta';
1335
+ const pluralName = dropdownId === 'category-multiselect' ? 'Categorias' : 'Contas';
1336
+
1337
+ if (count === total && total > 0) {
1338
+ label.textContent = pluralName; // Always keep clean label when all selected
1339
+ } else if (count === 0) {
1340
+ label.textContent = `Nenhuma ${name}`;
1341
+ } else {
1342
+ label.textContent = `${count} ${name}${count > 1 ? 's' : ''}`;
1343
+ }
1344
+ }
1345
+
1346
+ // Fetch categories and accounts to populate dropdowns
1347
+ async function fetchDropdownData() {
1348
+ try {
1349
+ const [catsRes, accsRes] = await Promise.all([
1350
+ fetch('/api/categories'),
1351
+ fetch('/api/accounts')
1352
+ ]);
1353
+
1354
+ if (catsRes.ok) {
1355
+ const cats = await catsRes.json();
1356
+ const optionsContainer = document.getElementById('category-multiselect-options');
1357
+ optionsContainer.innerHTML = '';
1358
+ selectedCategories.clear();
1359
+
1360
+ cats.sort((a,b) => a.name.localeCompare(b.name));
1361
+ // Add "Sem Categoria"
1362
+ cats.unshift({ id: 'none', name: 'Sem Categoria' });
1363
+ totalCategoriesCount = cats.length;
1364
+
1365
+ cats.forEach(c => {
1366
+ selectedCategories.add(c.name); // Default selected
1367
+
1368
+ const optionDiv = document.createElement('div');
1369
+ optionDiv.className = 'multiselect-option';
1370
+ optionDiv.innerHTML = `
1371
+ <label style="display: flex; align-items: center; gap: 0.5rem; width: 100%; cursor: pointer; margin: 0;">
1372
+ <input type="checkbox" value="${c.name}" checked>
1373
+ <span style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 200px;">${escapeHtml(c.name)}</span>
1374
+ </label>
1375
+ `;
1376
+
1377
+ optionDiv.querySelector('input').addEventListener('change', (e) => {
1378
+ if (e.target.checked) {
1379
+ selectedCategories.add(c.name);
1380
+ } else {
1381
+ selectedCategories.delete(c.name);
1382
+ }
1383
+ updateMultiselectButton('category-multiselect', selectedCategories.size, totalCategoriesCount);
1384
+ applyFiltersAndRender(false);
1385
+ });
1386
+
1387
+ optionsContainer.appendChild(optionDiv);
1388
+ });
1389
+
1390
+ updateMultiselectButton('category-multiselect', selectedCategories.size, totalCategoriesCount);
1391
+ }
1392
+
1393
+ if (accsRes.ok) {
1394
+ const accs = await accsRes.json();
1395
+ const optionsContainer = document.getElementById('account-multiselect-options');
1396
+ optionsContainer.innerHTML = '';
1397
+ selectedAccounts.clear();
1398
+ totalAccountsCount = accs.length;
1399
+
1400
+ accs.sort((a,b) => a.name.localeCompare(b.name));
1401
+
1402
+ // Separate into normal accounts and credit cards
1403
+ const normalAccounts = accs.filter(a => a.type !== 'credit');
1404
+ const creditCards = accs.filter(a => a.type === 'credit');
1405
+
1406
+ // Helper to create checkbox option
1407
+ const createOption = (a, isChecked) => {
1408
+ if (isChecked) {
1409
+ selectedAccounts.add(a.name);
1410
+ }
1411
+
1412
+ const optionDiv = document.createElement('div');
1413
+ optionDiv.className = 'multiselect-option';
1414
+ optionDiv.innerHTML = `
1415
+ <label style="display: flex; align-items: center; gap: 0.5rem; width: 100%; cursor: pointer; margin: 0;">
1416
+ <input type="checkbox" value="${a.name}" ${isChecked ? 'checked' : ''}>
1417
+ <span style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 200px;">${escapeHtml(a.name)}</span>
1418
+ </label>
1419
+ `;
1420
+
1421
+ optionDiv.querySelector('input').addEventListener('change', (e) => {
1422
+ if (e.target.checked) {
1423
+ selectedAccounts.add(a.name);
1424
+ } else {
1425
+ selectedAccounts.delete(a.name);
1426
+ }
1427
+ updateMultiselectButton('account-multiselect', selectedAccounts.size, totalAccountsCount);
1428
+ applyFiltersAndRender(false);
1429
+ });
1430
+
1431
+ return optionDiv;
1432
+ };
1433
+
1434
+ // Add normal accounts group (checked by default)
1435
+ if (normalAccounts.length > 0) {
1436
+ const header = document.createElement('div');
1437
+ header.style = 'font-size:0.65rem; font-weight:700; color:var(--text-dark); margin:0.35rem 0.25rem 0.15rem; text-transform:uppercase; letter-spacing:0.05em;';
1438
+ header.textContent = 'Contas';
1439
+ optionsContainer.appendChild(header);
1440
+
1441
+ normalAccounts.forEach(a => {
1442
+ optionsContainer.appendChild(createOption(a, true));
1443
+ });
1444
+ }
1445
+
1446
+ // Add credit cards group (unchecked by default)
1447
+ if (creditCards.length > 0) {
1448
+ const header = document.createElement('div');
1449
+ header.style = 'font-size:0.65rem; font-weight:700; color:var(--text-dark); margin:0.5rem 0.25rem 0.15rem; text-transform:uppercase; letter-spacing:0.05em;';
1450
+ header.textContent = 'Cartões de Crédito';
1451
+ optionsContainer.appendChild(header);
1452
+
1453
+ creditCards.forEach(a => {
1454
+ optionsContainer.appendChild(createOption(a, false));
1455
+ });
1456
+ }
1457
+
1458
+ updateMultiselectButton('account-multiselect', selectedAccounts.size, totalAccountsCount);
1459
+ }
1460
+ } catch (err) {
1461
+ console.error("Error loading filters data", err);
1462
+ }
1463
+ }
1464
+
1465
+ // Setup Select All / Clear All action links
1466
+ function setupActionLinks() {
1467
+ // Category links
1468
+ document.querySelector('#category-multiselect .select-all').addEventListener('click', (e) => {
1469
+ e.stopPropagation();
1470
+ const checkboxes = document.querySelectorAll('#category-multiselect-options input[type="checkbox"]');
1471
+ checkboxes.forEach(cb => {
1472
+ cb.checked = true;
1473
+ selectedCategories.add(cb.value);
1474
+ });
1475
+ updateMultiselectButton('category-multiselect', selectedCategories.size, totalCategoriesCount);
1476
+ applyFiltersAndRender(false);
1477
+ });
1478
+
1479
+ document.querySelector('#category-multiselect .clear-all').addEventListener('click', (e) => {
1480
+ e.stopPropagation();
1481
+ const checkboxes = document.querySelectorAll('#category-multiselect-options input[type="checkbox"]');
1482
+ checkboxes.forEach(cb => {
1483
+ cb.checked = false;
1484
+ selectedCategories.delete(cb.value);
1485
+ });
1486
+ updateMultiselectButton('category-multiselect', 0, totalCategoriesCount);
1487
+ applyFiltersAndRender(false);
1488
+ });
1489
+
1490
+ // Account links
1491
+ document.querySelector('#account-multiselect .select-all').addEventListener('click', (e) => {
1492
+ e.stopPropagation();
1493
+ const checkboxes = document.querySelectorAll('#account-multiselect-options input[type="checkbox"]');
1494
+ checkboxes.forEach(cb => {
1495
+ cb.checked = true;
1496
+ selectedAccounts.add(cb.value);
1497
+ });
1498
+ updateMultiselectButton('account-multiselect', selectedAccounts.size, totalAccountsCount);
1499
+ applyFiltersAndRender(false);
1500
+ });
1501
+
1502
+ document.querySelector('#account-multiselect .clear-all').addEventListener('click', (e) => {
1503
+ e.stopPropagation();
1504
+ const checkboxes = document.querySelectorAll('#account-multiselect-options input[type="checkbox"]');
1505
+ checkboxes.forEach(cb => {
1506
+ cb.checked = false;
1507
+ selectedAccounts.delete(cb.value);
1508
+ });
1509
+ updateMultiselectButton('account-multiselect', 0, totalAccountsCount);
1510
+ applyFiltersAndRender(false);
1511
+ });
1512
+ }
1513
+
1514
+ // Main data loader
1515
+ async function fetchDashboardData(focusToday = false) {
1516
+ tableLoading.classList.add('active');
1517
+ const month = parseInt(monthSelect.value);
1518
+ const year = parseInt(yearSelect.value);
1519
+
1520
+ try {
1521
+ async function fetchPendingTransactions(year, month) {
1522
+ let allItems = [];
1523
+ let cursor = null;
1524
+
1525
+ while (true) {
1526
+ const queryParams = new URLSearchParams({
1527
+ month: String(month),
1528
+ year: String(year),
1529
+ status: 'pending',
1530
+ sort: 'date',
1531
+ dir: 'desc'
1532
+ });
1533
+ if (cursor) {
1534
+ queryParams.set('cursor', cursor);
1535
+ }
1536
+
1537
+ const url = `/api/transactions?${queryParams.toString()}`;
1538
+ const res = await fetch(url);
1539
+ if (!res.ok) throw new Error(`HTTP error ${res.status}`);
1540
+
1541
+ const data = await res.json();
1542
+
1543
+ let items = [];
1544
+ let nextCursor = null;
1545
+ if (data && typeof data === 'object') {
1546
+ if (Array.isArray(data.items)) {
1547
+ items = data.items;
1548
+ nextCursor = data.nextCursor;
1549
+ } else if (Array.isArray(data)) {
1550
+ items = data;
1551
+ }
1552
+ }
1553
+
1554
+ allItems.push(...items);
1555
+
1556
+ if (!nextCursor) {
1557
+ break;
1558
+ }
1559
+ cursor = nextCursor;
1560
+ }
1561
+
1562
+ return allItems;
1563
+ }
1564
+
1565
+ allTransactions = await fetchPendingTransactions(year, month);
1566
+
1567
+ // Process totals & charts
1568
+ updateKPIs();
1569
+ applyFiltersAndRender(focusToday);
1570
+ renderCharts();
1571
+ } catch (err) {
1572
+ console.error("Dashboard Load Error:", err);
1573
+ showToast("Erro ao carregar dados do servidor. Tente novamente.", "error");
1574
+ } finally {
1575
+ tableLoading.classList.remove('active');
1576
+ }
1577
+ }
1578
+
1579
+ // Calculate KPI values — per-currency (never mixed into one total). The primary currency
1580
+ // (the user's base currency when the data has it, else the most active one) is the first
1581
+ // line; any other currency present is a secondary line, so a crypto account's activity
1582
+ // isn't silently dropped from these cards.
1583
+ function updateKPIs() {
1584
+ const incByCurrency = {};
1585
+ const expByCurrency = {};
1586
+
1587
+ allTransactions.forEach(t => {
1588
+ const currency = t.currency || window.DEFAULT_CURRENCY;
1589
+ const amt = t.amount || 0;
1590
+ if (t.type === 'income') {
1591
+ incByCurrency[currency] = (incByCurrency[currency] || 0) + amt;
1592
+ } else if (t.type === 'expense') {
1593
+ expByCurrency[currency] = (expByCurrency[currency] || 0) + amt;
1594
+ }
1595
+ });
1596
+
1597
+ primary = window.primaryCurrencyOf(window.mergeCurrencyMaps(incByCurrency, expByCurrency));
1598
+
1599
+ const currencies = Array.from(new Set([...Object.keys(incByCurrency), ...Object.keys(expByCurrency), primary]))
1600
+ .sort((a, b) => (a === primary ? -1 : b === primary ? 1 : a.localeCompare(b)));
1601
+
1602
+ const netByCurrency = {};
1603
+ currencies.forEach(c => {
1604
+ netByCurrency[c] = (incByCurrency[c] || 0) - (expByCurrency[c] || 0);
1605
+ });
1606
+
1607
+ const renderLines = (map) => {
1608
+ const primaryVal = map[primary] || 0;
1609
+ const secondary = currencies.filter(c => c !== primary && map[c]);
1610
+ return `<span>${window.formatMoney(primaryVal, primary)}</span>` +
1611
+ secondary.map(c => `<span class="secondary-val">${window.formatMoney(map[c], c)}</span>`).join('');
1612
+ };
1613
+
1614
+ // Populate cards
1615
+ document.getElementById('kpi-total-income').innerHTML = renderLines(incByCurrency);
1616
+ document.getElementById('kpi-total-expense').innerHTML = renderLines(expByCurrency);
1617
+
1618
+ const netEl = document.getElementById('kpi-net-balance');
1619
+ netEl.innerHTML = renderLines(netByCurrency);
1620
+
1621
+ // Adjust card style for the primary currency's net balance
1622
+ const netPrimary = netByCurrency[primary] || 0;
1623
+ const netCard = netEl.closest('.kpi-card');
1624
+ if (netPrimary >= 0) {
1625
+ netEl.style.color = 'var(--income-color)';
1626
+ netCard.style.setProperty('--accent-primary', 'var(--income-color)');
1627
+ } else {
1628
+ netEl.style.color = 'var(--expense-color)';
1629
+ netCard.style.setProperty('--accent-primary', 'var(--expense-color)');
1630
+ }
1631
+ }
1632
+
1633
+ // Toggle Grid Column Sort
1634
+ function toggleSort(column) {
1635
+ if (sortColumn === column) {
1636
+ sortDirection = sortDirection === 'asc' ? 'desc' : 'asc';
1637
+ } else {
1638
+ sortColumn = column;
1639
+ sortDirection = 'asc';
1640
+ }
1641
+ updateSortHeaders();
1642
+ applyFiltersAndRender(false);
1643
+ }
1644
+
1645
+ // Update Sorting icons inside table headers
1646
+ function updateSortHeaders() {
1647
+ const columns = ['date', 'type', 'description', 'category', 'account', 'amount'];
1648
+ columns.forEach(col => {
1649
+ const icon = document.getElementById(`sort-icon-${col}`);
1650
+ if (!icon) return;
1651
+
1652
+ if (sortColumn === col) {
1653
+ icon.className = `fa-solid fa-sort-${sortDirection === 'asc' ? 'up' : 'down'}`;
1654
+ icon.style.opacity = '1';
1655
+ icon.style.color = 'var(--accent-primary)';
1656
+ } else {
1657
+ icon.className = 'fa-solid fa-sort';
1658
+ icon.style.opacity = '0.3';
1659
+ icon.style.color = 'inherit';
1660
+ }
1661
+ });
1662
+ }
1663
+
1664
+ // Apply filters client-side & Render Table
1665
+ function applyFiltersAndRender(focusToday = false) {
1666
+ const query = searchInput.value.toLowerCase().trim();
1667
+ const typeVal = filterType.value;
1668
+
1669
+ filteredTransactions = allTransactions.filter(t => {
1670
+ // Search term (description or tag)
1671
+ const descMatch = t.description.toLowerCase().includes(query);
1672
+ const tagMatch = t.tags && t.tags.some(tag => tag.toLowerCase().includes(query));
1673
+ const matchQuery = !query || descMatch || tagMatch;
1674
+
1675
+ // Type filter
1676
+ const matchType = !typeVal || t.type === typeVal;
1677
+
1678
+ // Category multiselect matching
1679
+ const matchCategory = selectedCategories.has(t.categoryName || 'Sem Categoria');
1680
+
1681
+ // Account multiselect matching
1682
+ const matchAccount = selectedAccounts.has(t.accountName);
1683
+
1684
+ return matchQuery && matchType && matchCategory && matchAccount;
1685
+ });
1686
+
1687
+ // Perform Sorting based on sortColumn and sortDirection
1688
+ filteredTransactions.sort((a, b) => {
1689
+ let valA, valB;
1690
+
1691
+ if (sortColumn === 'date') {
1692
+ valA = a.date;
1693
+ valB = b.date;
1694
+ } else if (sortColumn === 'type') {
1695
+ valA = a.type.toLowerCase();
1696
+ valB = b.type.toLowerCase();
1697
+ } else if (sortColumn === 'description') {
1698
+ valA = a.description.toLowerCase();
1699
+ } else if (sortColumn === 'category') {
1700
+ valA = (a.categoryName || 'Sem Categoria').toLowerCase();
1701
+ valB = (b.categoryName || 'Sem Categoria').toLowerCase();
1702
+ } else if (sortColumn === 'account') {
1703
+ valA = a.accountName.toLowerCase();
1704
+ valB = b.accountName.toLowerCase();
1705
+ } else if (sortColumn === 'amount') {
1706
+ // Signed values: expense is negative, income is positive
1707
+ valA = a.type === 'expense' ? -a.amount : a.amount;
1708
+ valB = b.type === 'expense' ? -b.amount : b.amount;
1709
+ }
1710
+
1711
+ if (valA < valB) return sortDirection === 'asc' ? -1 : 1;
1712
+ if (valA > valB) return sortDirection === 'asc' ? 1 : -1;
1713
+
1714
+ // Secondary sort: keep it stable with date if sorting by other fields
1715
+ if (sortColumn !== 'date') {
1716
+ return a.date.localeCompare(b.date);
1717
+ }
1718
+ return 0;
1719
+ });
1720
+
1721
+ // Focus on page with today's date if requested
1722
+ if (focusToday && filteredTransactions.length > 0) {
1723
+ const localToday = new Date();
1724
+ const y = localToday.getFullYear();
1725
+ const m = String(localToday.getMonth() + 1).padStart(2, '0');
1726
+ const d = String(localToday.getDate()).padStart(2, '0');
1727
+ const todayStr = `${y}-${m}-${d}`;
1728
+
1729
+ // Find first index of today or in the future
1730
+ let targetIndex = filteredTransactions.findIndex(t => t.date >= todayStr);
1731
+ if (targetIndex === -1) {
1732
+ targetIndex = filteredTransactions.length - 1;
1733
+ }
1734
+
1735
+ if (targetIndex >= 0) {
1736
+ currentPage = Math.floor(targetIndex / itemsPerPage) + 1;
1737
+ } else {
1738
+ currentPage = 1;
1739
+ }
1740
+ } else if (!focusToday) {
1741
+ currentPage = 1;
1742
+ }
1743
+
1744
+ renderTable();
1745
+ }
1746
+
1747
+ // Render Table & Pagination
1748
+ function renderTable() {
1749
+ tableBody.innerHTML = '';
1750
+
1751
+ if (filteredTransactions.length === 0) {
1752
+ noDataMsg.style.display = 'block';
1753
+ document.getElementById('transactions-table').style.display = 'none';
1754
+ paginationText.textContent = 'Exibindo 0 de 0 transações';
1755
+ btnPrev.disabled = true;
1756
+ btnNext.disabled = true;
1757
+ return;
1758
+ }
1759
+
1760
+ noDataMsg.style.display = 'none';
1761
+ document.getElementById('transactions-table').style.display = 'table';
1762
+
1763
+ // Pagination boundaries
1764
+ const totalItems = filteredTransactions.length;
1765
+ const totalPages = Math.ceil(totalItems / itemsPerPage);
1766
+ const startIndex = (currentPage - 1) * itemsPerPage;
1767
+ const endIndex = Math.min(startIndex + itemsPerPage, totalItems);
1768
+
1769
+ const pageItems = filteredTransactions.slice(startIndex, endIndex);
1770
+
1771
+ // Get local formatted today's date
1772
+ const localToday = new Date();
1773
+ const y = localToday.getFullYear();
1774
+ const m = String(localToday.getMonth() + 1).padStart(2, '0');
1775
+ const d = String(localToday.getDate()).padStart(2, '0');
1776
+ const todayStr = `${y}-${m}-${d}`;
1777
+
1778
+ pageItems.forEach(t => {
1779
+ const tr = document.createElement('tr');
1780
+
1781
+ // Highlight row if date is today
1782
+ if (t.date === todayStr) {
1783
+ tr.className = 'today-row';
1784
+ }
1785
+
1786
+ // Formats
1787
+ const dateObj = new Date(t.date + 'T12:00:00'); // Prevent timezone offset shift
1788
+ const dateStr = dateObj.toLocaleDateString('pt-BR', { day: '2-digit', month: '2-digit' });
1789
+
1790
+ const isIncome = t.type === 'income';
1791
+ const badgeTypeClass = isIncome ? 'income' : 'expense';
1792
+
1793
+ const amtFormatted = window.formatMoney(t.amount, t.currency);
1794
+
1795
+ // Account indicator icon
1796
+ let accountIcon = '<i class="fa-solid fa-building-columns"></i>';
1797
+ if (t.accountName.toLowerCase().includes('card') || t.accountName.toLowerCase().includes('cartão') || t.cardName) {
1798
+ accountIcon = '<i class="fa-solid fa-credit-card"></i>';
1799
+ }
1800
+
1801
+ // Vibrant dynamic color mapping for category, splitting between income & expense types
1802
+ const catName = t.categoryName || 'Sem Categoria';
1803
+ const catColor = getCategoryColor(catName, t.type);
1804
+
1805
+ // Financial Trend Type Icon (Trending up for income, Trending down for expense)
1806
+ const typeIcon = isIncome
1807
+ ? `<i class="fa-solid fa-arrow-trend-up" style="color: var(--income-color); font-size: 0.95rem;" title="Receita"></i>`
1808
+ : `<i class="fa-solid fa-arrow-trend-down" style="color: var(--expense-color); font-size: 0.95rem;" title="Despesa"></i>`;
1809
+
1810
+ tr.innerHTML = `
1811
+ <td class="col-date">${dateStr}</td>
1812
+ <td style="text-align: center; vertical-align: middle;">${typeIcon}</td>
1813
+ <td class="col-desc">
1814
+ <div>${escapeHtml(t.description)}</div>
1815
+ ${t.tags && t.tags.length > 0 ? `<div style="margin-top: 4px; display:flex; gap: 4px; flex-wrap:wrap;">${t.tags.map(tag => `<span class="badge-cat" style="font-size:0.7rem; padding:1px 4px; border-radius:4px; color:#c084fc; border-color:rgba(192, 132, 252, 0.2); background:rgba(192, 132, 252, 0.05);"><i class="fa-solid fa-tag" style="font-size:0.6rem;"></i> ${escapeHtml(tag)}</span>`).join('')}</div>` : ''}
1816
+ </td>
1817
+ <td class="col-category">
1818
+ <span class="badge-cat" style="background: ${catColor.bg}; border-color: ${catColor.border}; color: ${catColor.text}; font-weight: 500;">
1819
+ ${escapeHtml(catName)}
1820
+ </span>
1821
+ </td>
1822
+ <td>
1823
+ <span class="badge-acc">
1824
+ ${accountIcon}
1825
+ <span>${escapeHtml(t.accountName)}</span>
1826
+ </span>
1827
+ </td>
1828
+ <td class="amount-cell ${badgeTypeClass}">${amtFormatted}</td>
1829
+ <td style="text-align: center;">
1830
+ <div class="actions-cell">
1831
+ <button class="action-btn btn-confirm-icon" title="Confirmar" onclick="confirmTx('${t.id}', '${escapeJsAttr(t.description)}', '${t.date}', ${t.amount})">
1832
+ <i class="fa-solid fa-check"></i>
1833
+ </button>
1834
+ <button class="action-btn btn-delete-icon" title="Excluir" onclick="deleteTx('${t.id}', '${escapeJsAttr(t.description)}')">
1835
+ <i class="fa-solid fa-trash-can"></i>
1836
+ </button>
1837
+ </div>
1838
+ </td>
1839
+ `;
1840
+ tableBody.appendChild(tr);
1841
+ });
1842
+
1843
+ // Update pagination text & buttons
1844
+ paginationText.textContent = `Exibindo ${startIndex + 1}–${endIndex} de ${totalItems} transações`;
1845
+ btnPrev.disabled = currentPage === 1;
1846
+ btnNext.disabled = currentPage === totalPages;
1847
+ }
1848
+
1849
+ // Modals management
1850
+ function openModal(id) {
1851
+ document.getElementById(id).classList.add('open');
1852
+ }
1853
+
1854
+ function closeModal(id) {
1855
+ document.getElementById(id).classList.remove('open');
1856
+ }
1857
+
1858
+ // Close modal on ESC key
1859
+ document.addEventListener('keydown', (e) => {
1860
+ if (e.key === 'Escape') {
1861
+ const activeModal = document.querySelector('.modal-overlay.open');
1862
+ if (activeModal) {
1863
+ closeModal(activeModal.id);
1864
+ }
1865
+ }
1866
+ });
1867
+
1868
+ // Confirm Transaction
1869
+ async function confirmTx(id, description, date, amount) {
1870
+ document.getElementById('confirm-tx-id').value = id;
1871
+ document.getElementById('confirm-tx-desc').textContent = description;
1872
+
1873
+ const dateInput = document.getElementById('confirm-tx-date');
1874
+ const todayStr = new Date().toISOString().split('T')[0];
1875
+
1876
+ if (dateInput._flatpickr) {
1877
+ dateInput._flatpickr.setDate(date || todayStr, true);
1878
+ dateInput._flatpickr.set('maxDate', todayStr);
1879
+ } else {
1880
+ dateInput.value = date || todayStr;
1881
+ dateInput.max = todayStr;
1882
+ }
1883
+
1884
+ document.getElementById('confirm-tx-amount').value = amount || '';
1885
+
1886
+ openModal('modal-confirm-tx');
1887
+ }
1888
+
1889
+ async function handleConfirmSubmit(e) {
1890
+ e.preventDefault();
1891
+ const id = document.getElementById('confirm-tx-id').value;
1892
+ const description = document.getElementById('confirm-tx-desc').textContent;
1893
+ const date = document.getElementById('confirm-tx-date').value;
1894
+ const amount = parseFloat(document.getElementById('confirm-tx-amount').value);
1895
+
1896
+ closeModal('modal-confirm-tx');
1897
+ tableLoading.classList.add('active');
1898
+
1899
+ try {
1900
+ const res = await fetch(`/api/transactions/${id}/confirm`, {
1901
+ method: 'POST',
1902
+ headers: { 'Content-Type': 'application/json' },
1903
+ body: JSON.stringify({ date, amount })
1904
+ });
1905
+
1906
+ if (!res.ok) {
1907
+ const errRes = await res.json();
1908
+ throw new Error(errRes.error?.message || "Erro ao confirmar transação");
1909
+ }
1910
+
1911
+ showToast(`Transação "${description}" confirmada com sucesso!`, 'success');
1912
+ await fetchDashboardData(false);
1913
+ } catch (err) {
1914
+ console.error("Confirmation error:", err);
1915
+ showToast(`Erro ao confirmar: ${err.message}`, 'error');
1916
+ } finally {
1917
+ tableLoading.classList.remove('active');
1918
+ }
1919
+ }
1920
+
1921
+ // Delete action
1922
+ async function deleteTx(id, description) {
1923
+ const tx = allTransactions.find(t => t.id === id);
1924
+ const isCard = tx && (tx.cardId || tx.billId || tx.cardName);
1925
+ const deleteUrl = isCard
1926
+ ? `/api/credit-cards/transactions/${id}?confirm=true`
1927
+ : `/api/accounts/transactions/${id}?confirm=true`;
1928
+
1929
+ if (!confirm(`Deseja excluir definitivamente a transação "${description}"?`)) {
1930
+ return;
1931
+ }
1932
+
1933
+ tableLoading.classList.add('active');
1934
+ try {
1935
+ const res = await fetch(deleteUrl, {
1936
+ method: 'DELETE'
1937
+ });
1938
+
1939
+ if (!res.ok) throw new Error("Erro ao excluir a transação");
1940
+
1941
+ showToast(`Transação "${description}" excluída com sucesso!`, 'success');
1942
+ // Reload dashboard data without losing current page focus
1943
+ await fetchDashboardData(false);
1944
+ } catch (err) {
1945
+ console.error("Deletion error:", err);
1946
+ showToast(`Erro ao excluir a transação: ${err.message}`, 'error');
1947
+ } finally {
1948
+ tableLoading.classList.remove('active');
1949
+ }
1950
+ }
1951
+
1952
+ // Keeps the charts' currency valid for the period: the user's pick while the period still
1953
+ // has expenses in it, else the primary currency. The selector only shows when the period
1954
+ // has expenses in more than one currency.
1955
+ function syncChartCurrency(expenses) {
1956
+ const codes = Array.from(new Set(expenses.map(t => t.currency || window.DEFAULT_CURRENCY)))
1957
+ .sort((a, b) => (a === primary ? -1 : b === primary ? 1 : a.localeCompare(b)));
1958
+ const fallback = codes.includes(primary) ? primary : (codes[0] ?? primary);
1959
+ if (!codes.includes(chartCurrency)) chartCurrencyChosen = false;
1960
+ chartCurrency = chartCurrencyChosen ? chartCurrency : fallback;
1961
+
1962
+ const group = document.getElementById('chart-currency-group');
1963
+ const select = document.getElementById('chart-currency-select');
1964
+ group.style.display = codes.length > 1 ? '' : 'none';
1965
+ select.innerHTML = codes.map(c => `<option value="${escapeHtml(c)}">${escapeHtml(c)}</option>`).join('');
1966
+ select.value = chartCurrency;
1967
+ translateChartTitles();
1968
+ }
1969
+
1970
+ function chartTitleText(key) {
1971
+ return t(key).replace('{currency}', chartCurrency);
1972
+ }
1973
+
1974
+ function translateChartTitles() {
1975
+ document.getElementById('chart-title-category').textContent = chartTitleText('pending_chart_by_category');
1976
+ document.getElementById('chart-title-top').textContent = chartTitleText('pending_chart_top_expenses');
1977
+ }
1978
+
1979
+ document.getElementById('chart-currency-select').addEventListener('change', (e) => {
1980
+ chartCurrency = e.target.value;
1981
+ chartCurrencyChosen = chartCurrency !== primary;
1982
+ renderCharts();
1983
+ });
1984
+
1985
+ // Render charts using Chart.js
1986
+ function renderCharts() {
1987
+ // Filter expenses only
1988
+ const expensesOnly = allTransactions.filter(t => t.type === 'expense');
1989
+
1990
+ syncChartCurrency(expensesOnly);
1991
+ const inChartCurrency = expensesOnly.filter(t => (t.currency || window.DEFAULT_CURRENCY) === chartCurrency);
1992
+
1993
+ // 1. Group by category (the selected currency only — never mixed)
1994
+ const catMap = {};
1995
+ inChartCurrency.forEach(t => {
1996
+ const cat = t.categoryName || 'Sem Categoria';
1997
+ catMap[cat] = (catMap[cat] || 0) + (t.amount || 0);
1998
+ });
1999
+
2000
+ const catLabels = Object.keys(catMap);
2001
+ const catValues = Object.values(catMap);
2002
+
2003
+ // Destroy existing doughnut chart if any
2004
+ if (catChartInstance) catChartInstance.destroy();
2005
+
2006
+ const catCtx = document.getElementById('categoryChart').getContext('2d');
2007
+ if (catLabels.length === 0) {
2008
+ catChartInstance = null;
2009
+ } else {
2010
+ // Map original vibrant colors to chart segments (these are always expenses)
2011
+ const catBgs = catLabels.map(label => getCategoryColor(label, 'expense').hex);
2012
+
2013
+ catChartInstance = new Chart(catCtx, {
2014
+ type: 'doughnut',
2015
+ data: {
2016
+ labels: catLabels,
2017
+ datasets: [{
2018
+ data: catValues,
2019
+ backgroundColor: catBgs,
2020
+ borderWidth: 1,
2021
+ borderColor: '#1e293b'
2022
+ }]
2023
+ },
2024
+ options: {
2025
+ responsive: true,
2026
+ maintainAspectRatio: false,
2027
+ plugins: {
2028
+ legend: {
2029
+ position: 'right',
2030
+ labels: {
2031
+ color: '#9ca3af',
2032
+ font: { family: 'Plus Jakarta Sans', size: 11 }
2033
+ }
2034
+ },
2035
+ tooltip: {
2036
+ callbacks: {
2037
+ label: function(context) {
2038
+ return ` ${context.label}: ${window.formatMoney(context.raw || 0, chartCurrency)}`;
2039
+ }
2040
+ }
2041
+ }
2042
+ }
2043
+ }
2044
+ });
2045
+ }
2046
+
2047
+ // 2. Top 5 Expenses (the selected currency)
2048
+ const top5 = inChartCurrency
2049
+ .slice()
2050
+ .sort((a, b) => b.amount - a.amount)
2051
+ .slice(0, 5);
2052
+
2053
+ const topLabels = top5.map(t => t.description.length > 20 ? t.description.slice(0, 18) + '...' : t.description);
2054
+ const topValues = top5.map(t => t.amount);
2055
+
2056
+ // Destroy existing bar chart if any
2057
+ if (topExpChartInstance) topExpChartInstance.destroy();
2058
+
2059
+ const topCtx = document.getElementById('topExpensesChart').getContext('2d');
2060
+ if (topLabels.length === 0) {
2061
+ topExpChartInstance = null;
2062
+ } else {
2063
+ topExpChartInstance = new Chart(topCtx, {
2064
+ type: 'bar',
2065
+ data: {
2066
+ labels: topLabels,
2067
+ datasets: [{
2068
+ label: `${t('label_value')} (${chartCurrency})`,
2069
+ data: topValues,
2070
+ backgroundColor: 'rgba(244, 63, 94, 0.85)', // Reverted to original vibrant rose
2071
+ borderColor: 'var(--expense-color)',
2072
+ borderWidth: 1,
2073
+ borderRadius: 6
2074
+ }]
2075
+ },
2076
+ options: {
2077
+ indexAxis: 'y',
2078
+ responsive: true,
2079
+ maintainAspectRatio: false,
2080
+ plugins: {
2081
+ legend: { display: false },
2082
+ tooltip: {
2083
+ callbacks: {
2084
+ label: function(context) {
2085
+ return ` ${window.formatMoney(context.raw, chartCurrency)}`;
2086
+ }
2087
+ }
2088
+ }
2089
+ },
2090
+ scales: {
2091
+ x: {
2092
+ grid: { color: 'rgba(255, 255, 255, 0.05)' },
2093
+ ticks: { color: '#9ca3af', font: { family: 'Plus Jakarta Sans' } }
2094
+ },
2095
+ y: {
2096
+ grid: { display: false },
2097
+ ticks: { color: '#9ca3af', font: { family: 'Plus Jakarta Sans' } }
2098
+ }
2099
+ }
2100
+ }
2101
+ });
2102
+ }
2103
+ }
2104
+
2105
+ // Escaping utilities
2106
+ function escapeHtml(str) {
2107
+ if (!str) return '';
2108
+ return str.replace(/&/g, "&amp;")
2109
+ .replace(/</g, "&lt;")
2110
+ .replace(/>/g, "&gt;")
2111
+ .replace(/"/g, "&quot;")
2112
+ .replace(/'/g, "&#039;");
2113
+ }
2114
+
2115
+ // JS Escaping
2116
+ // Escapes a value for safe embedding as a single-quoted JS string literal *inside* an
2117
+ // HTML attribute (e.g. onclick="fn('${escapeJsAttr(value)}')"). JS-escaping backslash+quote
2118
+ // alone is not enough: the outer onclick="..." attribute is double-quoted, and the HTML
2119
+ // parser (which finds the attribute's closing quote before any JS is parsed) doesn't
2120
+ // understand a JS \" escape — a raw '"' still ends the attribute early. HTML-escaping the
2121
+ // JS-escaped result closes that gap too.
2122
+ function escapeJsAttr(str) {
2123
+ if (!str) return '';
2124
+ return escapeHtml(String(str).replace(/\\/g, '\\\\').replace(/'/g, "\\'"));
2125
+ }
2126
+
2127
+ // Event listeners
2128
+ monthSelect.addEventListener('change', () => fetchDashboardData(true));
2129
+ yearSelect.addEventListener('change', () => fetchDashboardData(true));
2130
+ searchInput.addEventListener('input', () => applyFiltersAndRender(false));
2131
+ filterType.addEventListener('change', () => applyFiltersAndRender(false));
2132
+
2133
+ btnPrev.addEventListener('click', () => {
2134
+ if (currentPage > 1) {
2135
+ currentPage--;
2136
+ renderTable();
2137
+ }
2138
+ });
2139
+
2140
+ btnNext.addEventListener('click', () => {
2141
+ const totalPages = Math.ceil(filteredTransactions.length / itemsPerPage);
2142
+ if (currentPage < totalPages) {
2143
+ currentPage++;
2144
+ renderTable();
2145
+ }
2146
+ });
2147
+
2148
+ // App bootstrap
2149
+ async function init() {
2150
+ setupMultiselectToggles();
2151
+ setupActionLinks();
2152
+ updateSortHeaders(); // Show default sort icon
2153
+ await fetchDropdownData();
2154
+ await fetchDashboardData(true);
2155
+ flatpickr("input[type='date']", {
2156
+ locale: "pt",
2157
+ dateFormat: "Y-m-d",
2158
+ altInput: true,
2159
+ altFormat: "d/m/Y",
2160
+ allowInput: true,
2161
+ disableMobile: true
2162
+ });
2163
+ }
2164
+
2165
+
2166
+ // Translation engine and dictionaries
2167
+ var TRANSLATIONS = {
2168
+ en: {
2169
+ // Sidebar Menu
2170
+ tooltip_overview: "Overview",
2171
+ tooltip_pending: "Pending",
2172
+ tooltip_comparative: "Comparative",
2173
+ tooltip_projections: "Projections",
2174
+ tooltip_accounts: "Bank Accounts",
2175
+ tooltip_cards: "Credit Cards",
2176
+ menu_categories: "Categories",
2177
+ menu_dashboards: "Dashboards",
2178
+
2179
+ // Month names
2180
+ january: "January", february: "February", march: "March", april: "April", may: "May", june: "June",
2181
+ july: "July", august: "August", september: "September", october: "October", november: "November", december: "December",
2182
+
2183
+ // General UI terms
2184
+ reference_label: "Reference:",
2185
+ day_sun: "Sun", day_mon: "Mon", day_tue: "Tue", day_wed: "Wed", day_thu: "Thu", day_fri: "Fri", day_sat: "Sat",
2186
+ paid: "Paid", unpaid: "Unpaid", active: "Active", inactive: "Inactive",
2187
+
2188
+ // Overview Dashboard
2189
+ overview_title: "Overview",
2190
+ overview_subtitle: "Monthly financial summary, calendar, and quick shortcuts",
2191
+ accounts_balance: "Accounts Balance",
2192
+ expenses_month: "Expenses this Month",
2193
+ card_bills: "Credit Card Bills",
2194
+ incomes_month: "Incomes this Month",
2195
+ final_projection: "Final Projection:",
2196
+ recent_transactions: "Recent Transactions",
2197
+ due_calendar: "Daily Flow & Dues",
2198
+ expenses_distribution: "Expenses Distribution",
2199
+ quick_shortcuts: "Quick Shortcuts",
2200
+ new_transaction: "New Transaction",
2201
+ new_transfer: "New Transfer",
2202
+ new_category: "New Category",
2203
+ new_card: "New Card",
2204
+ new_account: "New Account",
2205
+ no_expenses_month: "No expenses recorded this month.",
2206
+ no_recent_transactions: "No recent transactions found.",
2207
+ no_dues_period: "No transactions due in this period.",
2208
+ income: "Income",
2209
+ expense: "Expense",
2210
+ paid_reconciled: "Paid / Reconciled",
2211
+
2212
+ // Projections / Heatmap Dashboard
2213
+ projections_title: "Recurring & Installment Projections",
2214
+ projections_subtitle: "Advanced visual mapping and projection of active recurrences and installments for the next months",
2215
+ projection_label: "Projection:",
2216
+ months_3: "3 Months",
2217
+ months_6: "6 Months",
2218
+ months_9: "9 Months",
2219
+ months_12: "12 Months",
2220
+ heatmap_income_title: "Recurrent / Installment Incomes",
2221
+ heatmap_expense_title: "Recurrent / Installment Expenses",
2222
+ total: "Total",
2223
+ no_recurrent_incomes: "No active recurrent or installment incomes in the selected semester.",
2224
+ no_recurrent_expenses: "No active recurrent or installment expenses in the selected semester.",
2225
+ modal_details_title: "Projection Breakdown",
2226
+ modal_details_subtitle: "Details of projected transactions for the category and month",
2227
+ col_date: "Date",
2228
+ col_desc: "Description",
2229
+ col_value: "Value",
2230
+ col_status: "Status",
2231
+ btn_close: "Close",
2232
+
2233
+ // Comparative Dashboard
2234
+ comparative_title: "Comparative Dashboard",
2235
+ comparative_subtitle: "Analysis and comparison of monthly incomes vs expenses, and category limits",
2236
+ month_summary_title: "Month Summary",
2237
+ cat_spending_title: "Spending by Category",
2238
+ card_limits_title: "Category Budgets & Limits",
2239
+ col_category: "Category",
2240
+ col_limit: "Budget Limit",
2241
+ col_spent: "Spent",
2242
+ col_status_limit: "Status",
2243
+ col_percentage: "Percentage",
2244
+ within_limit: "Within Limit",
2245
+ exceeded: "Exceeded",
2246
+ reception: "Incomes",
2247
+ deduction: "Expenses",
2248
+ net_balance: "Net Balance",
2249
+ performance: "Financial Health",
2250
+ no_spending_month: "No category spend recorded this month.",
2251
+
2252
+ // Accounts Dashboard
2253
+ accounts_title: "Bank Accounts",
2254
+ accounts_subtitle: "Manage accounts, checking balances, and reviewing statements",
2255
+ active_account_statement: "Account Statement",
2256
+ btn_new_transaction: "New Transaction",
2257
+ btn_new_transfer: "New Transfer",
2258
+ search_description_placeholder: "Type to search...",
2259
+ filter_type_label: "Type",
2260
+ filter_type_all: "All",
2261
+ filter_type_income: "Incomes",
2262
+ filter_type_expense: "Expenses",
2263
+ col_actions: "Actions",
2264
+ action_confirm: "Confirm",
2265
+ action_edit: "Edit",
2266
+ action_delete: "Delete",
2267
+ no_transactions_account: "No transactions recorded for this account in the selected month.",
2268
+ confirm_delete_title: "Are you sure you want to permanently delete this transaction?",
2269
+ modal_new_tx_title: "New Transaction",
2270
+ modal_new_transfer_title: "New Transfer",
2271
+ label_account: "Account",
2272
+ label_description: "Description",
2273
+ label_value: "Value",
2274
+ label_date: "Date",
2275
+ label_category: "Category / Subcategory",
2276
+ label_type: "Type",
2277
+ label_status: "Status",
2278
+ status_pending: "Pending",
2279
+ status_confirmed: "Paid / Confirmed",
2280
+ btn_cancel: "Cancel",
2281
+ btn_save: "Save",
2282
+ label_origin: "Origin Account",
2283
+ label_destination: "Destination Account",
2284
+ modal_confirm_tx_title: "Confirm Transaction",
2285
+ label_confirm_date: "Confirmation Date",
2286
+
2287
+ // Pending Dashboard
2288
+ pending_title: "Pending Transactions",
2289
+ pending_subtitle: "Monitoring and quick confirmation of pending or future transactions",
2290
+ pending_kpi_total: "Total Pending",
2291
+ pending_kpi_incomes: "Pending Incomes",
2292
+ pending_kpi_expenses: "Pending Expenses",
2293
+ pending_chart_incomes: "Pending Incomes Trend",
2294
+ pending_chart_expenses: "Pending Expenses Trend",
2295
+ pending_chart_by_category: "Expenses by Category ({currency})",
2296
+ pending_chart_top_expenses: "Top Pending Expenses ({currency})",
2297
+ pending_chart_currency_label: "Currency:",
2298
+ btn_confirm: "Confirm",
2299
+ btn_edit: "Edit",
2300
+ btn_delete: "Delete",
2301
+ no_pending_transactions: "No pending transactions found for this period.",
2302
+ toast_success_confirm: "Transaction confirmed successfully!",
2303
+
2304
+ // Categories Dashboard
2305
+ categories_title: "Category Management",
2306
+ categories_subtitle: "Visualize, search, and manage categories and subcategories in a clean tree list",
2307
+ btn_new_category: "New Category",
2308
+ search_category_placeholder: "Search categories...",
2309
+ col_type: "Type",
2310
+ col_actions_cat: "Actions",
2311
+ subcategories_label: "Subcategories",
2312
+ no_subcategories: "No subcategories registered.",
2313
+ modal_new_cat_title: "New Category",
2314
+ modal_new_subcat_title: "New Subcategory",
2315
+ label_name: "Name",
2316
+ label_color: "Color",
2317
+ label_parent_category: "Parent Category (Read-Only)",
2318
+ toast_success_cat: "Category created successfully!",
2319
+ toast_success_subcat: "Subcategory created successfully!",
2320
+
2321
+ // Cards Dashboard
2322
+ cards_title: "Credit Cards",
2323
+ cards_subtitle: "Manage credit cards, credit limits, and statement history",
2324
+ card_bill_details: "Card Bill Details",
2325
+ btn_pay_bill: "Pay Bill",
2326
+ btn_revert_payment: "Revert Payment",
2327
+ bill_status: "Bill Status:",
2328
+ status_open: "Open",
2329
+ status_closed: "Closed",
2330
+ status_paid: "Paid",
2331
+ no_card_transactions: "No transactions recorded for this card bill in the selected cycle.",
2332
+
2333
+ // Dashboards Manager Dashboard
2334
+ dashboards_title: "Dashboards Monitor",
2335
+ dashboards_subtitle: "List, view source, and upload patty dashboards",
2336
+ col_dashboard: "Dashboard",
2337
+ col_last_update: "Last Updated",
2338
+ btn_view_source: "View Source",
2339
+ btn_download: "Download",
2340
+ upload_new_dashboard: "Upload New Dashboard",
2341
+ placeholder_dashboard_name: "Dashboard Name (e.g. pending)",
2342
+ upload_instructions: "Select or drop HTML file here to upload",
2343
+ btn_upload: "Upload",
2344
+ modal_source_title: "HTML Source Code",
2345
+
2346
+ // Tags Management
2347
+ menu_tags: "Tags",
2348
+ tags_title: "Tag Management",
2349
+ tags_subtitle: "Manage tags to label and organize your transactions",
2350
+ panel_title_tags: "Active Tags",
2351
+ btn_new_tag: "New Tag",
2352
+ label_tag_name: "Tag Name",
2353
+ placeholder_tag_name: "E.g. work, travel, refund",
2354
+ empty_tags_message: "No tags registered.",
2355
+ btn_save: "Save",
2356
+ btn_cancel: "Cancel",
2357
+ toast_success_tag_created: 'Tag "{name}" created successfully!',
2358
+ toast_success_tag_deleted: 'Tag "{name}" deleted successfully!',
2359
+ confirm_delete_tag: 'Are you sure you want to delete tag "{name}"?\n(This action will remove the tag from all linked transactions)'
2360
+ },
2361
+ pt: {
2362
+ // Sidebar Menu
2363
+ tooltip_overview: "Visão Geral",
2364
+ tooltip_pending: "Pendentes",
2365
+ tooltip_comparative: "Comparativo",
2366
+ tooltip_projections: "Projeções",
2367
+ tooltip_accounts: "Contas Bancárias",
2368
+ tooltip_cards: "Cartões de Crédito",
2369
+ menu_categories: "Categorias",
2370
+ menu_dashboards: "Dashboards",
2371
+
2372
+ // Month names
2373
+ january: "Janeiro", february: "Fevereiro", march: "Março", april: "Abril", may: "Maio", june: "Junho",
2374
+ july: "Julho", august: "Agosto", september: "Setembro", october: "Outubro", november: "Novembro", december: "Dezembro",
2375
+
2376
+ // General UI terms
2377
+ reference_label: "Referência:",
2378
+ day_sun: "Dom", day_mon: "Seg", day_tue: "Ter", day_wed: "Qua", day_thu: "Qui", day_fri: "Sex", day_sat: "Sáb",
2379
+ paid: "Pago", unpaid: "Não Pago", active: "Ativo", inactive: "Inativo",
2380
+
2381
+ // Overview Dashboard
2382
+ overview_title: "Visão Geral",
2383
+ overview_subtitle: "Consolidado financeiro mensal, calendário e atalhos rápidos",
2384
+ accounts_balance: "Saldo em Contas",
2385
+ expenses_month: "Despesas do Mês",
2386
+ card_bills: "Faturas de Cartão",
2387
+ incomes_month: "Receitas do Mês",
2388
+ final_projection: "Projeção Final:",
2389
+ recent_transactions: "Lançamentos Recentes",
2390
+ due_calendar: "Fluxo Diário",
2391
+ expenses_distribution: "Distribuição de Despesas",
2392
+ quick_shortcuts: "Atalhos Rápidos",
2393
+ new_transaction: "Novo Lançamento",
2394
+ new_transfer: "Nova Transferência",
2395
+ new_category: "Nova Categoria",
2396
+ new_card: "Novo Cartão",
2397
+ new_account: "Nova Conta",
2398
+ no_expenses_month: "Sem despesas registradas neste mês.",
2399
+ no_recent_transactions: "Nenhuma transação recente encontrada.",
2400
+ no_dues_period: "Sem vencimentos neste período.",
2401
+ income: "Receita",
2402
+ expense: "Despesa",
2403
+ paid_reconciled: "Pago / Conciliado",
2404
+
2405
+ // Projections / Heatmap Dashboard
2406
+ projections_title: "Projeção de Recorrências e Parcelas",
2407
+ projections_subtitle: "Mapeamento visual avançado e projeção de recorrências e parcelas ativas para os próximos meses",
2408
+ projection_label: "Projeção:",
2409
+ months_3: "3 Meses",
2410
+ months_6: "6 Meses",
2411
+ months_9: "9 Meses",
2412
+ months_12: "12 Meses",
2413
+ heatmap_income_title: "Receitas Recorrentes / Parceladas",
2414
+ heatmap_expense_title: "Despesas Recorrentes / Parceladas",
2415
+ total: "Total",
2416
+ no_recurrent_incomes: "Nenhuma receita recorrente/parcelada ativa no semestre.",
2417
+ no_recurrent_expenses: "Nenhuma despesa recorrente/parcelada ativa no semestre.",
2418
+ modal_details_title: "Detalhamento de Projeções",
2419
+ modal_details_subtitle: "Detalhes das transações projetadas para a categoria e mês",
2420
+ col_date: "Data",
2421
+ col_desc: "Descrição",
2422
+ col_value: "Valor",
2423
+ col_status: "Status",
2424
+ btn_close: "Fechar",
2425
+
2426
+ // Comparative Dashboard
2427
+ comparative_title: "Dashboard Comparativo",
2428
+ comparative_subtitle: "Análise e comparação mensal de receitas vs despesas e limites por categoria",
2429
+ month_summary_title: "Resumo do Mês",
2430
+ cat_spending_title: "Gastos por Categoria",
2431
+ card_limits_title: "Orçamentos e Limites de Categorias",
2432
+ col_category: "Categoria",
2433
+ col_limit: "Limite de Orçamento",
2434
+ col_spent: "Gasto",
2435
+ col_status_limit: "Status",
2436
+ col_percentage: "Porcentagem",
2437
+ within_limit: "Dentro do Limite",
2438
+ exceeded: "Excedido",
2439
+ reception: "Receitas",
2440
+ deduction: "Despesas",
2441
+ net_balance: "Saldo Líquido",
2442
+ performance: "Saúde Financeira",
2443
+ no_spending_month: "Sem despesas registradas por categoria neste mês.",
2444
+
2445
+ // Accounts Dashboard
2446
+ accounts_title: "Minhas Contas",
2447
+ accounts_subtitle: "Gerencie contas, consulte saldos e revise extratos",
2448
+ active_account_statement: "Extrato de Conta",
2449
+ btn_new_transaction: "Novo Lançamento",
2450
+ btn_new_transfer: "Nova Transferência",
2451
+ search_description_placeholder: "Digite para filtrar...",
2452
+ filter_type_label: "Tipo",
2453
+ filter_type_all: "Todos",
2454
+ filter_type_income: "Receitas",
2455
+ filter_type_expense: "Despesas",
2456
+ col_actions: "Ações",
2457
+ action_confirm: "Confirmar",
2458
+ action_edit: "Editar",
2459
+ action_delete: "Excluir",
2460
+ no_transactions_account: "Nenhum lançamento nesta conta para o mês selecionado.",
2461
+ confirm_delete_title: "Deseja excluir definitivamente a transação?",
2462
+ modal_new_tx_title: "Novo Lançamento",
2463
+ modal_new_transfer_title: "Nova Transferência",
2464
+ label_account: "Conta",
2465
+ label_description: "Descrição",
2466
+ label_value: "Valor",
2467
+ label_date: "Data",
2468
+ label_category: "Categoria / Subcategoria",
2469
+ label_type: "Tipo",
2470
+ label_status: "Status",
2471
+ status_pending: "Pendente",
2472
+ status_confirmed: "Pago / Confirmado",
2473
+ btn_cancel: "Cancelar",
2474
+ btn_save: "Salvar",
2475
+ label_origin: "Conta Origem",
2476
+ label_destination: "Conta Destino",
2477
+ modal_confirm_tx_title: "Confirmar Lançamento",
2478
+ label_confirm_date: "Data da Confirmação",
2479
+
2480
+ // Pending Dashboard
2481
+ pending_title: "Transações Pendentes",
2482
+ pending_subtitle: "Monitoramento e confirmação rápida de lançamentos pendentes ou futuros",
2483
+ pending_kpi_total: "Total Pendente",
2484
+ pending_kpi_incomes: "Receitas Pendentes",
2485
+ pending_kpi_expenses: "Despesas Pendentes",
2486
+ pending_chart_incomes: "Tendência de Receitas Pendentes",
2487
+ pending_chart_expenses: "Tendência de Despesas Pendentes",
2488
+ pending_chart_by_category: "Despesas por Categoria ({currency})",
2489
+ pending_chart_top_expenses: "Maiores Despesas Previstas ({currency})",
2490
+ pending_chart_currency_label: "Moeda:",
2491
+ btn_confirm: "Confirmar",
2492
+ btn_edit: "Editar",
2493
+ btn_delete: "Excluir",
2494
+ no_pending_transactions: "Nenhuma transação pendente encontrada para este período.",
2495
+ toast_success_confirm: "Transação confirmada com sucesso!",
2496
+
2497
+ // Categories Dashboard
2498
+ categories_title: "Gerenciamento de Categorias",
2499
+ categories_subtitle: "Visualize, pesquise e gerencie categorias e subcategorias em árvore",
2500
+ btn_new_category: "Nova Categoria",
2501
+ search_category_placeholder: "Pesquisar categorias...",
2502
+ col_type: "Tipo",
2503
+ col_actions_cat: "Ações",
2504
+ subcategories_label: "Subcategorias",
2505
+ no_subcategories: "Nenhuma subcategoria cadastrada.",
2506
+ modal_new_cat_title: "Nova Categoria",
2507
+ modal_new_subcat_title: "Nova Subcategoria",
2508
+ label_name: "Nome",
2509
+ label_color: "Cor",
2510
+ label_parent_category: "Categoria Pai (Somente Leitura)",
2511
+ toast_success_cat: "Categoria criada com sucesso!",
2512
+ toast_success_subcat: "Subcategoria criada com sucesso!",
2513
+
2514
+ // Cards Dashboard
2515
+ cards_title: "Cartões de Crédito",
2516
+ cards_subtitle: "Gerencie cartões de crédito, limites e histórico de faturas",
2517
+ card_bill_details: "Detalhamento de Fatura",
2518
+ btn_pay_bill: "Pagar Fatura",
2519
+ btn_revert_payment: "Estornar Pagamento",
2520
+ bill_status: "Status da Fatura:",
2521
+ status_open: "Aberta",
2522
+ status_closed: "Fechada",
2523
+ status_paid: "Paga",
2524
+ no_card_transactions: "Nenhuma transação registrada nesta fatura para o ciclo selecionado.",
2525
+
2526
+ // Dashboards Manager Dashboard
2527
+ dashboards_title: "Monitor de Dashboards",
2528
+ dashboards_subtitle: "Liste, visualize o código fonte e envie dashboards para o servidor do patty",
2529
+ col_dashboard: "Dashboard",
2530
+ col_last_update: "Última Atualização",
2531
+ btn_view_source: "Ver Código",
2532
+ btn_download: "Baixar HTML",
2533
+ upload_new_dashboard: "Enviar Novo Dashboard",
2534
+ placeholder_dashboard_name: "Nome do Dashboard (ex: pending)",
2535
+ upload_instructions: "Selecione ou solte o arquivo HTML aqui para upload",
2536
+ btn_upload: "Fazer Upload",
2537
+ modal_source_title: "Código Fonte HTML",
2538
+
2539
+ // Tags Management
2540
+ menu_tags: "Tags",
2541
+ tags_title: "Gerenciar Tags",
2542
+ tags_subtitle: "Gerencie as tags utilizadas para rotular e categorizar suas transações",
2543
+ panel_title_tags: "Tags Ativas",
2544
+ btn_new_tag: "Nova Tag",
2545
+ label_tag_name: "Nome da Tag",
2546
+ placeholder_tag_name: "Ex: trabalho, viagem, reembolso",
2547
+ empty_tags_message: "Nenhuma tag cadastrada.",
2548
+ btn_save: "Salvar",
2549
+ btn_cancel: "Cancelar",
2550
+ toast_success_tag_created: 'Tag "{name}" criada com sucesso!',
2551
+ toast_success_tag_deleted: 'Tag "{name}" excluída com sucesso!',
2552
+ confirm_delete_tag: 'Deseja realmente excluir a tag "{name}"?\n(Esta ação removerá a tag de todas as transações vinculadas)'
2553
+ },
2554
+ es: {
2555
+ // Sidebar Menu
2556
+ tooltip_overview: "Vista General",
2557
+ tooltip_pending: "Pendientes",
2558
+ tooltip_comparative: "Comparativo",
2559
+ tooltip_projections: "Proyecciones",
2560
+ tooltip_accounts: "Cuentas Bancárias",
2561
+ tooltip_cards: "Tarjetas de Crédito",
2562
+ menu_categories: "Categorías",
2563
+ menu_dashboards: "Dashboards",
2564
+
2565
+ // Month names
2566
+ january: "Enero", february: "Febrero", march: "Marzo", april: "Abril", may: "Mayo", june: "Junio",
2567
+ july: "Julio", august: "Agosto", september: "Septiembre", october: "Octubre", november: "Noviembre", december: "Diciembre",
2568
+
2569
+ // General UI terms
2570
+ reference_label: "Referencia:",
2571
+ day_sun: "Dom", day_mon: "Lun", day_tue: "Mar", day_wed: "Mié", day_thu: "Jue", day_fri: "Vie", day_sat: "Sáb",
2572
+ paid: "Pagado", unpaid: "No Pagado", active: "Activo", inactive: "Inactivo",
2573
+
2574
+ // Overview Dashboard
2575
+ overview_title: "Vista General",
2576
+ overview_subtitle: "Resumen financiero mensual, calendario y accesos rápidos",
2577
+ accounts_balance: "Saldo en Cuentas",
2578
+ expenses_month: "Gastos del Mes",
2579
+ card_bills: "Facturas de Tarjeta",
2580
+ incomes_month: "Ingresos del Mes",
2581
+ final_projection: "Proyección Final:",
2582
+ recent_transactions: "Transacciones Recientes",
2583
+ due_calendar: "Calendario de Pagos",
2584
+ expenses_distribution: "Distribución de Gastos",
2585
+ quick_shortcuts: "Accesos Rápidos",
2586
+ new_transaction: "Nueva Transacción",
2587
+ new_transfer: "Nueva Transferencia",
2588
+ new_category: "Nueva Categoría",
2589
+ new_card: "Nueva Tarjeta",
2590
+ new_account: "Nueva Cuenta",
2591
+ no_expenses_month: "No hay gastos registrados este mes.",
2592
+ no_recent_transactions: "No se encontraron transacciones recientes.",
2593
+ no_dues_period: "Sin vencimientos en este período.",
2594
+ income: "Ingreso",
2595
+ expense: "Gasto",
2596
+ paid_reconciled: "Pagado / Conciliado",
2597
+
2598
+ // Projections / Heatmap Dashboard
2599
+ projections_title: "Proyección de Recurrencias y Cuotas",
2600
+ projections_subtitle: "Mapeo visual avanzado y proyección de recurrencias y cuotas activas para los próximos meses",
2601
+ projection_label: "Proyección:",
2602
+ months_3: "3 Meses",
2603
+ months_6: "6 Meses",
2604
+ months_9: "9 Meses",
2605
+ months_12: "12 Meses",
2606
+ heatmap_income_title: "Ingresos Recurrentes / Cuotas",
2607
+ heatmap_expense_title: "Gastos Recurrentes / Cuotas",
2608
+ total: "Total",
2609
+ no_recurrent_incomes: "Ningún ingreso recurrente o en cuotas activo en el semestre seleccionado.",
2610
+ no_recurrent_expenses: "Ningún gasto recurrente o en cuotas activo en el semestre seleccionado.",
2611
+ modal_details_title: "Detalle de Proyecciones",
2612
+ modal_details_subtitle: "Detalles de transacciones proyectadas para la categoría y mes",
2613
+ col_date: "Fecha",
2614
+ col_desc: "Descripción",
2615
+ col_value: "Valor",
2616
+ col_status: "Estado",
2617
+ btn_close: "Cerrar",
2618
+
2619
+ // Comparative Dashboard
2620
+ comparative_title: "Dashboard Comparativo",
2621
+ comparative_subtitle: "Análisis y comparación mensual de ingresos vs gastos y límites por categoría",
2622
+ month_summary_title: "Resumen del Mes",
2623
+ cat_spending_title: "Gastos por Categoría",
2624
+ card_limits_title: "Presupuestos y Límites de Categorías",
2625
+ col_category: "Categoría",
2626
+ col_limit: "Límite de Presupuesto",
2627
+ col_spent: "Gastado",
2628
+ col_status_limit: "Estado",
2629
+ col_percentage: "Porcentaje",
2630
+ within_limit: "Dentro del Límite",
2631
+ exceeded: "Excedido",
2632
+ reception: "Ingresos",
2633
+ deduction: "Gastos",
2634
+ net_balance: "Saldo Neto",
2635
+ performance: "Salud Financiera",
2636
+ no_spending_month: "No hay gastos registrados por categoría este mes.",
2637
+
2638
+ // Accounts Dashboard
2639
+ accounts_title: "Cuentas Bancarias",
2640
+ accounts_subtitle: "Administre cuentas, consulte saldos y revise extractos",
2641
+ active_account_statement: "Extracto de Cuenta",
2642
+ btn_new_transaction: "Nueva Transacción",
2643
+ btn_new_transfer: "Nueva Transferencia",
2644
+ search_description_placeholder: "Escriba para filtrar...",
2645
+ filter_type_label: "Tipo",
2646
+ filter_type_all: "Todos",
2647
+ filter_type_income: "Ingresos",
2648
+ filter_type_expense: "Gastos",
2649
+ col_actions: "Acciones",
2650
+ action_confirm: "Confirmar",
2651
+ action_edit: "Editar",
2652
+ action_delete: "Eliminar",
2653
+ no_transactions_account: "No hay transacciones registradas en esta cuenta en el mes seleccionado.",
2654
+ confirm_delete_title: "¿Está seguro de eliminar definitivamente esta transacción?",
2655
+ modal_new_tx_title: "Nueva Transacción",
2656
+ modal_new_transfer_title: "Nueva Transferencia",
2657
+ label_account: "Cuenta",
2658
+ label_description: "Descripción",
2659
+ label_value: "Valor",
2660
+ label_date: "Fecha",
2661
+ label_category: "Categoría / Subcategoría",
2662
+ label_type: "Tipo",
2663
+ label_status: "Estado",
2664
+ status_pending: "Pendiente",
2665
+ status_confirmed: "Pagado / Confirmado",
2666
+ btn_cancel: "Cancelar",
2667
+ btn_save: "Guardar",
2668
+ label_origin: "Cuenta Origen",
2669
+ label_destination: "Cuenta Destino",
2670
+ modal_confirm_tx_title: "Confirmar Transacción",
2671
+ label_confirm_date: "Fecha de Confirmación",
2672
+
2673
+ // Pending Dashboard
2674
+ pending_title: "Transacciones Pendientes",
2675
+ pending_subtitle: "Monitoreo y confirmación rápida de transacciones pendientes o futuras",
2676
+ pending_kpi_total: "Total Pendiente",
2677
+ pending_kpi_incomes: "Ingresos Pendientes",
2678
+ pending_kpi_expenses: "Gastos Pendientes",
2679
+ pending_chart_incomes: "Tendencia de Ingresos Pendientes",
2680
+ pending_chart_expenses: "Tendencia de Gastos Pendientes",
2681
+ pending_chart_by_category: "Gastos por Categoría ({currency})",
2682
+ pending_chart_top_expenses: "Mayores Gastos Previstos ({currency})",
2683
+ pending_chart_currency_label: "Moneda:",
2684
+ btn_confirm: "Confirmar",
2685
+ btn_edit: "Editar",
2686
+ btn_delete: "Eliminar",
2687
+ no_pending_transactions: "No se encontraron transacciones pendientes en este período.",
2688
+ toast_success_confirm: "¡Transacción confirmada con éxito!",
2689
+
2690
+ // Categories Dashboard
2691
+ categories_title: "Gestión de Categorías",
2692
+ categories_subtitle: "Visualice, busque y gestione categorías y subcategorías en árbol",
2693
+ btn_new_category: "Nueva Categoría",
2694
+ search_category_placeholder: "Buscar categorías...",
2695
+ col_type: "Tipo",
2696
+ col_actions_cat: "Acciones",
2697
+ subcategories_label: "Subcategorías",
2698
+ no_subcategories: "Ninguna subcategoría registrada.",
2699
+ modal_new_cat_title: "Nueva Categoría",
2700
+ modal_new_subcat_title: "Nueva Subcategoría",
2701
+ label_name: "Nombre",
2702
+ label_color: "Color",
2703
+ label_parent_category: "Categoría Padre (Solo Lectura)",
2704
+ toast_success_cat: "¡Categoría creada con éxito!",
2705
+ toast_success_subcat: "¡Subcategoría creada con éxito!",
2706
+
2707
+ // Cards Dashboard
2708
+ cards_title: "Tarjetas de Crédito",
2709
+ cards_subtitle: "Gestione tarjetas de crédito, límites y facturas",
2710
+ card_bill_details: "Detalle de Factura",
2711
+ btn_pay_bill: "Pagar Factura",
2712
+ btn_revert_payment: "Revertir Pago",
2713
+ bill_status: "Estado de la Factura:",
2714
+ status_open: "Abierta",
2715
+ status_closed: "Cerrada",
2716
+ status_paid: "Pagada",
2717
+ no_card_transactions: "Ninguna transacción registrada en esta factura para el ciclo seleccionado.",
2718
+
2719
+ // Dashboards Manager Dashboard
2720
+ dashboards_title: "Gestor de Dashboards",
2721
+ dashboards_subtitle: "Liste, vea el código fuente y suba dashboards al servidor de patty",
2722
+ col_dashboard: "Dashboard",
2723
+ col_last_update: "Última Actualización",
2724
+ btn_view_source: "Ver Código",
2725
+ btn_download: "Descargar HTML",
2726
+ upload_new_dashboard: "Subir Nuevo Dashboard",
2727
+ placeholder_dashboard_name: "Nombre del Dashboard (ej: pending)",
2728
+ upload_instructions: "Seleccione o arrastre el archivo HTML aquí para subir",
2729
+ btn_upload: "Subir Dashboard",
2730
+ modal_source_title: "Código Fuente HTML",
2731
+
2732
+ // Tags Management
2733
+ menu_tags: "Etiquetas",
2734
+ tags_title: "Administrar Etiquetas",
2735
+ tags_subtitle: "Administre las etiquetas utilizadas para etiquetar y organizar sus transacciones",
2736
+ panel_title_tags: "Etiquetas Activas",
2737
+ btn_new_tag: "Nueva Etiqueta",
2738
+ label_tag_name: "Nombre de la Etiqueta",
2739
+ placeholder_tag_name: "Ej: trabajo, viaje, reembolso",
2740
+ empty_tags_message: "No hay etiquetas registradas.",
2741
+ btn_save: "Guardar",
2742
+ btn_cancel: "Cancelar",
2743
+ toast_success_tag_created: '¡Etiqueta "{name}" creada con éxito!',
2744
+ toast_success_tag_deleted: '¡Etiqueta "{name}" eliminada con éxito!',
2745
+ confirm_delete_tag: '¿Realmente deseja eliminar la etiqueta "{name}"?\n(Esta acción eliminará la etiqueta de todas las transacciones vinculadas)'
2746
+ }
2747
+ };
2748
+
2749
+ var currentLocale = 'en'; // English as default
2750
+
2751
+ // Helper to translate in JS
2752
+ function t(key) {
2753
+ const tDict = TRANSLATIONS[currentLocale] || TRANSLATIONS['en'];
2754
+ return tDict[key] || key;
2755
+ }
2756
+
2757
+ async function checkLocale() {
2758
+ try {
2759
+ const res = await fetch('/api/status');
2760
+ if (res.ok) {
2761
+ const data = await res.json();
2762
+ if (data.locale && TRANSLATIONS[data.locale]) {
2763
+ currentLocale = data.locale;
2764
+ }
2765
+ }
2766
+ } catch (err) {
2767
+ console.error("Failed to read locale preferences:", err);
2768
+ }
2769
+ translatePage();
2770
+ }
2771
+
2772
+ function translatePage() {
2773
+ const tDict = TRANSLATIONS[currentLocale] || TRANSLATIONS['en'];
2774
+
2775
+ // 1. Static texts
2776
+ document.querySelectorAll('[data-i18n]').forEach(el => {
2777
+ const key = el.getAttribute('data-i18n');
2778
+ if (tDict[key]) {
2779
+ const icon = el.querySelector('i');
2780
+ if (icon) {
2781
+ const iconOuter = icon.outerHTML;
2782
+ el.innerHTML = iconOuter + ' ' + tDict[key];
2783
+ } else {
2784
+ el.textContent = tDict[key].replace('{currency}', chartCurrency);
2785
+ }
2786
+ }
2787
+ });
2788
+
2789
+ // 2. Placeholders
2790
+ document.querySelectorAll('[data-i18n-placeholder]').forEach(el => {
2791
+ const key = el.getAttribute('data-i18n-placeholder');
2792
+ if (tDict[key]) {
2793
+ el.placeholder = tDict[key];
2794
+ }
2795
+ });
2796
+
2797
+ // 3. Tooltips
2798
+ document.querySelectorAll('[data-i18n-tooltip]').forEach(el => {
2799
+ const key = el.getAttribute('data-i18n-tooltip');
2800
+ if (tDict[key]) {
2801
+ el.setAttribute('data-tooltip', tDict[key]);
2802
+ }
2803
+ });
2804
+
2805
+ // 4. Document title translation
2806
+ if (tDict['overview_title'] && document.title.includes("Overview") || document.title.includes("Visão")) {
2807
+ // dynamic title update fallback if needed
2808
+ }
2809
+
2810
+ // 5. Translate select months
2811
+ const monthSelects = [
2812
+ document.getElementById('month-select'),
2813
+ document.getElementById('start-month-select')
2814
+ ];
2815
+ monthSelects.forEach(monthSelect => {
2816
+ if (monthSelect) {
2817
+ const monthKeys = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
2818
+ Array.from(monthSelect.options).forEach((opt, idx) => {
2819
+ const key = monthKeys[idx];
2820
+ if (tDict[key]) {
2821
+ opt.textContent = tDict[key];
2822
+ }
2823
+ });
2824
+ }
2825
+ });
2826
+
2827
+ // 6. Translate projection months select options (3, 6, 9, 12 months)
2828
+ const hmSelect = document.getElementById('heatmap-months-select');
2829
+ if (hmSelect) {
2830
+ Array.from(hmSelect.options).forEach(opt => {
2831
+ const val = opt.value;
2832
+ const key = `months_${val}`;
2833
+ if (tDict[key]) {
2834
+ opt.textContent = tDict[key];
2835
+ }
2836
+ });
2837
+ }
2838
+
2839
+ // Automatically initialize/refresh custom selects on all pages
2840
+ if (typeof initCustomSelects === 'function') {
2841
+ initCustomSelects();
2842
+ }
2843
+ }
2844
+
2845
+ // Custom Select Component implementation
2846
+ function initCustomSelects() {
2847
+ document.querySelectorAll('select.select-custom').forEach(select => {
2848
+ if (select.nextElementSibling && select.nextElementSibling.classList.contains('select-container-custom')) {
2849
+ // Already initialized, just sync selected value
2850
+ const container = select.nextElementSibling;
2851
+ const triggerSpan = container.querySelector('.select-trigger-custom span');
2852
+ const selectedOpt = select.options[select.selectedIndex];
2853
+ if (selectedOpt && triggerSpan) {
2854
+ triggerSpan.textContent = selectedOpt.textContent;
2855
+ }
2856
+ return;
2857
+ }
2858
+ select.style.display = 'none';
2859
+ const container = document.createElement('div');
2860
+ container.className = 'select-container-custom';
2861
+
2862
+ // Match specific element custom min-widths
2863
+ if (select.id === 'heatmap-months-select') {
2864
+ container.style.minWidth = '110px';
2865
+ } else if (select.id === 'year-select') {
2866
+ container.style.minWidth = '90px';
2867
+ } else if (select.id === 'filter-type') {
2868
+ container.style.minWidth = '115px';
2869
+ }
2870
+
2871
+ const trigger = document.createElement('div');
2872
+ trigger.className = 'select-trigger-custom';
2873
+ const triggerSpan = document.createElement('span');
2874
+ trigger.appendChild(triggerSpan);
2875
+ container.appendChild(trigger);
2876
+ const optionsContainer = document.createElement('div');
2877
+ optionsContainer.className = 'select-options-custom';
2878
+ container.appendChild(optionsContainer);
2879
+
2880
+ function syncSelected() {
2881
+ const selectedOpt = select.options[select.selectedIndex] || select.options[0];
2882
+ if (selectedOpt) {
2883
+ triggerSpan.textContent = selectedOpt.textContent;
2884
+ Array.from(optionsContainer.children).forEach(child => {
2885
+ if (child.getAttribute('data-value') === select.value) {
2886
+ child.classList.add('selected');
2887
+ } else {
2888
+ child.classList.remove('selected');
2889
+ }
2890
+ });
2891
+ }
2892
+ }
2893
+
2894
+ function populateOptions() {
2895
+ optionsContainer.innerHTML = '';
2896
+ Array.from(select.options).forEach(opt => {
2897
+ const optDiv = document.createElement('div');
2898
+ optDiv.className = 'select-option-custom';
2899
+ optDiv.textContent = opt.textContent;
2900
+ optDiv.setAttribute('data-value', opt.value);
2901
+ optDiv.addEventListener('click', (e) => {
2902
+ e.stopPropagation();
2903
+ select.value = opt.value;
2904
+ select.dispatchEvent(new Event('change'));
2905
+ syncSelected();
2906
+ container.classList.remove('open');
2907
+ });
2908
+ optionsContainer.appendChild(optDiv);
2909
+ });
2910
+ }
2911
+
2912
+ populateOptions();
2913
+ syncSelected();
2914
+
2915
+ trigger.addEventListener('click', (e) => {
2916
+ e.stopPropagation();
2917
+ const isOpen = container.classList.contains('open');
2918
+ document.querySelectorAll('.select-container-custom').forEach(el => {
2919
+ el.classList.remove('open');
2920
+ });
2921
+ if (!isOpen) {
2922
+ populateOptions();
2923
+ syncSelected();
2924
+ container.classList.add('open');
2925
+ setTimeout(() => {
2926
+ const selectedEl = optionsContainer.querySelector('.select-option-custom.selected');
2927
+ if (selectedEl) {
2928
+ const itemHeight = selectedEl.offsetHeight || 36;
2929
+ optionsContainer.scrollTop = Math.max(0, selectedEl.offsetTop - itemHeight);
2930
+ }
2931
+ }, 10);
2932
+ }
2933
+ });
2934
+
2935
+ select.parentNode.insertBefore(container, select.nextSibling);
2936
+ select.addEventListener('change', syncSelected);
2937
+
2938
+ // Watch for dynamic options updates
2939
+ const observer = new MutationObserver(() => {
2940
+ syncSelected();
2941
+ });
2942
+ observer.observe(select, { childList: true, subtree: true });
2943
+
2944
+ setTimeout(syncSelected, 200);
2945
+ setTimeout(syncSelected, 1000);
2946
+ });
2947
+
2948
+ // Global click listener to close options dropdowns when clicking outside
2949
+ if (!window.customSelectGlobalBound) {
2950
+ window.customSelectGlobalBound = true;
2951
+ document.addEventListener('click', () => {
2952
+ document.querySelectorAll('.select-container-custom').forEach(el => {
2953
+ el.classList.remove('open');
2954
+ });
2955
+ });
2956
+ }
2957
+ }
2958
+
2959
+ init();
2960
+ checkLocale();
2961
+
2962
+ // ADR-027 Live-update listener
2963
+ window.onAppDataChanged = function(entities) {
2964
+ var affected = entities.some(function(tag) {
2965
+ return ['transaction', 'recurring', 'account', 'category', 'creditCard', 'tag', 'userSettings'].indexOf(tag) !== -1;
2966
+ });
2967
+ if (affected) {
2968
+ console.log("pending refetching due to entity change:", entities);
2969
+ init();
2970
+ }
2971
+ };
2972
+
2973
+ </script>