@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,4032 @@
1
+ <style>
2
+ .dashboard-container {
3
+ max-width: 1400px;
4
+ margin: 0 auto;
5
+ display: flex;
6
+ flex-direction: column;
7
+ gap: 1.5rem;
8
+ }
9
+
10
+ .controls-area {
11
+ display: flex;
12
+ align-items: center;
13
+ gap: 1rem;
14
+ background: var(--panel-bg);
15
+ border: 1px solid var(--panel-border);
16
+ padding: 0.5rem 1rem;
17
+ border-radius: 14px;
18
+ backdrop-filter: blur(12px);
19
+ }
20
+
21
+ .controls-area label {
22
+ font-size: 0.85rem;
23
+ font-weight: 600;
24
+ color: var(--text-muted);
25
+ text-transform: uppercase;
26
+ letter-spacing: 0.05em;
27
+ }
28
+
29
+ .select-custom {
30
+ background: rgba(255, 255, 255, 0.05);
31
+ border: 1px solid var(--panel-border);
32
+ color: var(--text-main);
33
+ padding: 0.5rem 1.5rem 0.5rem 0.75rem;
34
+ border-radius: 8px;
35
+ font-family: var(--font-family);
36
+ font-weight: 500;
37
+ cursor: pointer;
38
+ outline: none;
39
+ transition: var(--transition-smooth);
40
+ appearance: none;
41
+ background-image: url("data:image/svg+xml;charset=UTF-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%239ca3af' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");
42
+ background-repeat: no-repeat;
43
+ background-position: right 8px center;
44
+ background-size: 16px;
45
+ }
46
+
47
+ .select-custom:focus {
48
+ border-color: var(--accent-primary);
49
+ box-shadow: 0 0 0 2px var(--accent-primary-glow);
50
+ }
51
+
52
+ /* Premium Credit Cards Section */
53
+ .cards-section {
54
+ display: flex;
55
+ flex-direction: column;
56
+ gap: 1rem;
57
+ }
58
+
59
+ .section-title {
60
+ font-size: 1.1rem;
61
+ font-weight: 600;
62
+ color: var(--text-muted);
63
+ text-transform: uppercase;
64
+ letter-spacing: 0.05em;
65
+ display: flex;
66
+ align-items: center;
67
+ gap: 0.5rem;
68
+ }
69
+
70
+ .section-title i {
71
+ color: var(--accent-primary);
72
+ }
73
+
74
+ .cards-carousel {
75
+ display: grid;
76
+ grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
77
+ gap: 1.5rem;
78
+ }
79
+
80
+ .credit-card-mockup {
81
+ height: 200px;
82
+ border-radius: 18px;
83
+ padding: 1.5rem;
84
+ display: flex;
85
+ flex-direction: column;
86
+ justify-content: space-between;
87
+ position: relative;
88
+ overflow: hidden;
89
+ cursor: pointer;
90
+ box-shadow: var(--card-shadow);
91
+ transition: var(--transition-smooth);
92
+ border: 2px solid transparent;
93
+ user-select: none;
94
+ }
95
+
96
+ .credit-card-mockup::after {
97
+ content: '';
98
+ position: absolute;
99
+ top: -50%;
100
+ left: -50%;
101
+ width: 200%;
102
+ height: 200%;
103
+ background: linear-gradient(
104
+ 45deg,
105
+ transparent 45%,
106
+ rgba(255, 255, 255, 0.05) 50%,
107
+ transparent 55%
108
+ );
109
+ transform: rotate(30deg);
110
+ transition: transform 0.8s ease-in-out;
111
+ }
112
+
113
+ .credit-card-mockup:hover {
114
+ transform: translateY(-8px) scale(1.02);
115
+ }
116
+
117
+ .credit-card-mockup:hover::after {
118
+ transform: rotate(30deg) translate(15%, 15%);
119
+ }
120
+
121
+ .credit-card-mockup.active {
122
+ border-color: rgba(255, 255, 255, 0.5);
123
+ box-shadow: 0 0 25px rgba(139, 92, 246, 0.4);
124
+ }
125
+
126
+ /* Specific card styles */
127
+ .personnalite-black {
128
+ background: linear-gradient(135deg, #12131a 0%, #1e1f29 60%, #2a2c3a 100%);
129
+ border: 1px solid rgba(212, 175, 55, 0.2);
130
+ }
131
+ .personnalite-black.active {
132
+ border-color: #d4af37;
133
+ box-shadow: 0 0 25px rgba(212, 175, 55, 0.35);
134
+ }
135
+
136
+ .personnalite-infinite {
137
+ background: linear-gradient(135deg, #0b1120 0%, #111b36 60%, #1a2a54 100%);
138
+ border: 1px solid rgba(0, 200, 255, 0.15);
139
+ }
140
+ .personnalite-infinite.active {
141
+ border-color: #00c8ff;
142
+ box-shadow: 0 0 25px rgba(0, 200, 255, 0.35);
143
+ }
144
+
145
+ .ultravioleta-black {
146
+ background: linear-gradient(135deg, #1b0a2a 0%, #2e104e 60%, #4a154b 100%);
147
+ border: 1px solid rgba(168, 85, 247, 0.2);
148
+ }
149
+ .ultravioleta-black.active {
150
+ border-color: #a855f7;
151
+ box-shadow: 0 0 25px rgba(168, 85, 247, 0.35);
152
+ }
153
+
154
+ /* Card internals */
155
+ .card-header-mock {
156
+ display: flex;
157
+ justify-content: space-between;
158
+ align-items: flex-start;
159
+ }
160
+
161
+ .card-name-mock {
162
+ font-size: 0.95rem;
163
+ font-weight: 700;
164
+ letter-spacing: 0.05em;
165
+ color: #fff;
166
+ text-shadow: 0 2px 4px rgba(0,0,0,0.5);
167
+ }
168
+
169
+ .personnalite-black .card-name-mock { color: #e5c158; }
170
+ .personnalite-infinite .card-name-mock { color: #60d6ff; }
171
+ .ultravioleta-black .card-name-mock { color: #d8b4fe; }
172
+
173
+ .card-chip {
174
+ width: 38px;
175
+ height: 28px;
176
+ background: linear-gradient(135deg, #e5c158 0%, #b8860b 100%);
177
+ border-radius: 6px;
178
+ position: relative;
179
+ box-shadow: inset 0 1px 3px rgba(0,0,0,0.3);
180
+ }
181
+ .personnalite-infinite .card-chip {
182
+ background: linear-gradient(135deg, #cbd5e1 0%, #94a3b8 100%);
183
+ }
184
+
185
+ .card-chip::before {
186
+ content: '';
187
+ position: absolute;
188
+ top: 4px; left: 6px; right: 6px; bottom: 4px;
189
+ border: 1px solid rgba(0,0,0,0.15);
190
+ border-radius: 4px;
191
+ }
192
+
193
+ .card-number-mock {
194
+ font-size: 1.1rem;
195
+ letter-spacing: 0.15em;
196
+ color: rgba(255, 255, 255, 0.9);
197
+ font-family: monospace;
198
+ text-shadow: 0 2px 3px rgba(0,0,0,0.8);
199
+ margin: 0.75rem 0;
200
+ }
201
+
202
+ .card-footer-mock {
203
+ display: flex;
204
+ justify-content: space-between;
205
+ align-items: flex-end;
206
+ }
207
+
208
+ .card-holder-mock {
209
+ font-size: 0.7rem;
210
+ color: var(--text-muted);
211
+ text-transform: uppercase;
212
+ letter-spacing: 0.1em;
213
+ }
214
+
215
+ .card-holder-name {
216
+ font-size: 0.85rem;
217
+ font-weight: 600;
218
+ color: #fff;
219
+ margin-top: 2px;
220
+ letter-spacing: 0.05em;
221
+ }
222
+
223
+ .card-limit-mock {
224
+ text-align: right;
225
+ }
226
+
227
+ .card-limit-label {
228
+ font-size: 0.65rem;
229
+ color: var(--text-muted);
230
+ text-transform: uppercase;
231
+ letter-spacing: 0.05em;
232
+ }
233
+
234
+ .card-limit-value {
235
+ font-size: 0.95rem;
236
+ font-weight: 700;
237
+ color: #fff;
238
+ }
239
+
240
+ .card-indicator-badge {
241
+ position: absolute;
242
+ top: 1rem;
243
+ right: 1.5rem;
244
+ font-size: 0.65rem;
245
+ font-weight: 700;
246
+ text-transform: uppercase;
247
+ letter-spacing: 0.05em;
248
+ padding: 0.2rem 0.5rem;
249
+ border-radius: 4px;
250
+ background: rgba(255,255,255,0.06);
251
+ border: 1px solid rgba(255,255,255,0.1);
252
+ }
253
+ .card-indicator-badge.open { color: var(--warning-color); border-color: rgba(245, 158, 11, 0.3); background: rgba(245, 158, 11, 0.1); }
254
+ .card-indicator-badge.closed { color: var(--expense-color); border-color: rgba(244, 63, 94, 0.3); background: rgba(244, 63, 94, 0.1); }
255
+ .card-indicator-badge.paid { color: var(--income-color); border-color: rgba(16, 185, 129, 0.3); background: rgba(16, 185, 129, 0.1); }
256
+
257
+ /* Main Workspace split: Bill info & Transactions list */
258
+ .workspace-grid {
259
+ display: grid;
260
+ grid-template-columns: 1.1fr 2fr;
261
+ gap: 1.5rem;
262
+ }
263
+
264
+ @media (max-width: 1024px) {
265
+ .workspace-grid {
266
+ grid-template-columns: 1fr;
267
+ }
268
+ }
269
+
270
+ /* base: ui/app.css (#164) */
271
+ .panel {
272
+ padding: 1.75rem;
273
+ display: flex;
274
+ flex-direction: column;
275
+ gap: 1.5rem;
276
+ position: relative;
277
+ }
278
+
279
+ /* Bill Cycle Navigation Tabs */
280
+ .bill-cycle-tabs {
281
+ display: flex;
282
+ background: rgba(0,0,0,0.2);
283
+ border: 1px solid var(--panel-border);
284
+ border-radius: 12px;
285
+ padding: 0.25rem;
286
+ gap: 0.25rem;
287
+ }
288
+
289
+ .bill-tab {
290
+ flex: 1;
291
+ background: transparent;
292
+ border: none;
293
+ color: var(--text-muted);
294
+ padding: 0.5rem;
295
+ border-radius: 8px;
296
+ font-family: var(--font-family);
297
+ font-size: 0.8rem;
298
+ font-weight: 600;
299
+ cursor: pointer;
300
+ transition: var(--transition-smooth);
301
+ text-align: center;
302
+ }
303
+
304
+ .bill-tab.active {
305
+ background: var(--accent-primary);
306
+ color: #fff;
307
+ box-shadow: 0 4px 12px var(--accent-primary-glow);
308
+ }
309
+
310
+ /* Bill info panels */
311
+ .bill-info-box {
312
+ display: flex;
313
+ flex-direction: column;
314
+ gap: 1rem;
315
+ background: rgba(0, 0, 0, 0.15);
316
+ border: 1px solid var(--panel-border);
317
+ border-radius: 16px;
318
+ padding: 1.25rem;
319
+ }
320
+
321
+ .bill-info-row {
322
+ display: flex;
323
+ justify-content: space-between;
324
+ align-items: center;
325
+ }
326
+
327
+ .bill-info-label {
328
+ font-size: 0.8rem;
329
+ color: var(--text-muted);
330
+ text-transform: uppercase;
331
+ letter-spacing: 0.05em;
332
+ }
333
+
334
+ .bill-info-value {
335
+ font-weight: 600;
336
+ font-size: 0.9rem;
337
+ }
338
+
339
+ .bill-status-badge {
340
+ display: inline-flex;
341
+ align-items: center;
342
+ gap: 0.35rem;
343
+ font-size: 0.8rem;
344
+ font-weight: 700;
345
+ text-transform: uppercase;
346
+ letter-spacing: 0.05em;
347
+ padding: 0.3rem 0.65rem;
348
+ border-radius: 6px;
349
+ }
350
+ .bill-status-badge.open { color: var(--warning-color); background: rgba(245, 158, 11, 0.1); border: 1px solid rgba(245, 158, 11, 0.2); }
351
+ .bill-status-badge.closed { color: var(--expense-color); background: rgba(244, 63, 94, 0.1); border: 1px solid rgba(244, 63, 94, 0.2); }
352
+ .bill-status-badge.paid { color: var(--income-color); background: rgba(16, 185, 129, 0.1); border: 1px solid rgba(16, 185, 129, 0.2); }
353
+
354
+ .bill-total-area {
355
+ text-align: center;
356
+ padding: 1rem 0;
357
+ border-top: 1px solid rgba(255,255,255,0.04);
358
+ border-bottom: 1px solid rgba(255,255,255,0.04);
359
+ }
360
+
361
+ .bill-total-label {
362
+ font-size: 0.75rem;
363
+ color: var(--text-muted);
364
+ text-transform: uppercase;
365
+ letter-spacing: 0.08em;
366
+ margin-bottom: 0.25rem;
367
+ }
368
+
369
+ .bill-total-amount {
370
+ font-size: 2.2rem;
371
+ font-weight: 800;
372
+ color: #fff;
373
+ }
374
+
375
+ .bill-actions {
376
+ display: flex;
377
+ flex-direction: column;
378
+ gap: 0.75rem;
379
+ }
380
+
381
+ /* base: ui/app.css (#164) */
382
+ .btn-action-primary {
383
+ width: 100%;
384
+ padding: 0.75rem;
385
+ border-radius: 12px;
386
+ font-family: var(--font-family);
387
+ display: flex;
388
+ justify-content: center;
389
+ box-shadow: 0 4px 15px var(--accent-primary-glow);
390
+ }
391
+
392
+ .btn-action-primary:hover:not(:disabled) {
393
+ transform: translateY(-2px);
394
+ background: #9d76fd;
395
+ box-shadow: 0 6px 20px rgba(139, 92, 246, 0.55);
396
+ }
397
+
398
+ .btn-action-primary:disabled {
399
+ opacity: 0.5;
400
+ cursor: not-allowed;
401
+ box-shadow: none;
402
+ }
403
+
404
+ .btn-action-secondary {
405
+ width: 100%;
406
+ background: rgba(255,255,255,0.04);
407
+ border: 1px solid var(--panel-border);
408
+ color: var(--text-main);
409
+ padding: 0.75rem;
410
+ border-radius: 12px;
411
+ font-family: var(--font-family);
412
+ font-weight: 600;
413
+ cursor: pointer;
414
+ transition: var(--transition-smooth);
415
+ display: flex;
416
+ justify-content: center;
417
+ align-items: center;
418
+ gap: 0.5rem;
419
+ }
420
+
421
+ .btn-action-secondary:hover:not(:disabled) {
422
+ background: rgba(255,255,255,0.08);
423
+ border-color: rgba(255,255,255,0.15);
424
+ }
425
+
426
+ .btn-action-secondary:disabled {
427
+ opacity: 0.5;
428
+ cursor: not-allowed;
429
+ }
430
+
431
+ /* Panel Header styling */
432
+ .panel-header {
433
+ display: flex;
434
+ justify-content: space-between;
435
+ align-items: center;
436
+ flex-wrap: wrap;
437
+ gap: 1rem;
438
+ margin-bottom: 1rem;
439
+ }
440
+
441
+ .panel-title {
442
+ display: flex;
443
+ align-items: center;
444
+ gap: 0.5rem;
445
+ font-size: 1.1rem;
446
+ font-weight: 600;
447
+ }
448
+
449
+ /* Split modal container rules */
450
+ .modal-box.split-modal {
451
+ max-width: 780px;
452
+ }
453
+
454
+ .modal-split-body {
455
+ display: grid;
456
+ grid-template-columns: 1.1fr 1fr;
457
+ gap: 1.5rem;
458
+ }
459
+
460
+ .modal-column-left {
461
+ display: flex;
462
+ flex-direction: column;
463
+ }
464
+
465
+ .modal-column-right {
466
+ display: flex;
467
+ flex-direction: column;
468
+ }
469
+
470
+ .textarea-large {
471
+ width: 100%;
472
+ flex: 1;
473
+ min-height: 180px;
474
+ background: rgba(255, 255, 255, 0.04);
475
+ border: 1px solid var(--panel-border);
476
+ color: var(--text-main);
477
+ padding: 0.75rem;
478
+ border-radius: 8px;
479
+ font-family: var(--font-family);
480
+ outline: none;
481
+ transition: var(--transition-smooth);
482
+ resize: none;
483
+ font-size: 0.9rem;
484
+ }
485
+ .textarea-large:focus {
486
+ border-color: var(--accent-primary);
487
+ background: rgba(255, 255, 255, 0.06);
488
+ box-shadow: 0 0 10px rgba(139, 92, 246, 0.25);
489
+ }
490
+
491
+ /* Table & Transactions Panel styling */
492
+ .panel-header-buttons {
493
+ display: flex;
494
+ align-items: center;
495
+ gap: 0.75rem;
496
+ }
497
+
498
+ .btn-mini-add {
499
+ background: rgba(16, 185, 129, 0.15);
500
+ border: 1px solid rgba(16, 185, 129, 0.3);
501
+ color: var(--income-color);
502
+ padding: 0.4rem 0.8rem;
503
+ border-radius: 8px;
504
+ font-family: var(--font-family);
505
+ font-size: 0.8rem;
506
+ font-weight: 600;
507
+ cursor: pointer;
508
+ transition: var(--transition-smooth);
509
+ display: flex;
510
+ align-items: center;
511
+ gap: 0.35rem;
512
+ }
513
+
514
+ .btn-mini-add:hover {
515
+ background: rgba(16, 185, 129, 0.25);
516
+ transform: translateY(-1px);
517
+ }
518
+
519
+ .table-container {
520
+ overflow-x: auto;
521
+ border-radius: 14px;
522
+ border: 1px solid var(--panel-border);
523
+ background: rgba(0, 0, 0, 0.1);
524
+ }
525
+
526
+ table {
527
+ width: 100%;
528
+ border-collapse: collapse;
529
+ text-align: left;
530
+ font-size: 0.9rem;
531
+ }
532
+
533
+ th {
534
+ background: rgba(255, 255, 255, 0.02);
535
+ color: var(--text-muted);
536
+ font-weight: 600;
537
+ padding: 1rem;
538
+ border-bottom: 1px solid var(--panel-border);
539
+ text-transform: uppercase;
540
+ font-size: 0.75rem;
541
+ letter-spacing: 0.05em;
542
+ }
543
+
544
+ th.sortable {
545
+ cursor: pointer;
546
+ user-select: none;
547
+ transition: var(--transition-smooth);
548
+ }
549
+
550
+ th.sortable:hover {
551
+ color: var(--text-main);
552
+ background: rgba(255, 255, 255, 0.04);
553
+ }
554
+
555
+ th i {
556
+ margin-left: 0.35rem;
557
+ font-size: 0.8rem;
558
+ transition: var(--transition-smooth);
559
+ }
560
+
561
+ td {
562
+ padding: 0.9rem 1rem;
563
+ border-bottom: 1px solid rgba(255, 255, 255, 0.03);
564
+ vertical-align: middle;
565
+ color: var(--text-main);
566
+ }
567
+
568
+ tr:hover td {
569
+ background: rgba(255, 255, 255, 0.02);
570
+ }
571
+
572
+ tr:last-child td {
573
+ border-bottom: none;
574
+ }
575
+
576
+ .col-date { color: var(--text-muted); white-space: nowrap; }
577
+ .col-desc { font-weight: 500; }
578
+ .amount-cell { font-weight: 700; text-align: right; white-space: nowrap; color: var(--expense-color); }
579
+ .badge-cat {
580
+ background: rgba(255, 255, 255, 0.04);
581
+ border: 1px solid var(--panel-border);
582
+ padding: 0.25rem 0.6rem;
583
+ border-radius: 6px;
584
+ font-size: 0.8rem;
585
+ color: var(--text-muted);
586
+ }
587
+
588
+ .actions-cell {
589
+ display: flex;
590
+ justify-content: center;
591
+ align-items: center;
592
+ gap: 0.75rem;
593
+ }
594
+
595
+ .action-btn {
596
+ background: transparent;
597
+ border: none;
598
+ cursor: pointer;
599
+ font-size: 1rem;
600
+ display: inline-flex;
601
+ align-items: center;
602
+ justify-content: center;
603
+ width: 28px;
604
+ height: 28px;
605
+ border-radius: 6px;
606
+ transition: var(--transition-smooth);
607
+ }
608
+
609
+ .btn-change-icon { color: var(--accent-primary); opacity: 0.65; }
610
+ .btn-change-icon:hover { opacity: 1; transform: scale(1.25); }
611
+
612
+ .btn-confirm-icon { color: var(--income-color); opacity: 0.65; }
613
+ .btn-confirm-icon:hover { opacity: 1; transform: scale(1.25); }
614
+
615
+ .btn-delete-icon { color: var(--expense-color); opacity: 0.65; }
616
+ .btn-delete-icon:hover { opacity: 1; transform: scale(1.25); }
617
+
618
+ /* Loader (.loading-overlay/.spinner base: ui/app.css, #164) */
619
+ .loading-overlay {
620
+ width: 100%; height: 100%;
621
+ border-radius: 24px;
622
+ opacity: 0; pointer-events: none;
623
+ transition: opacity 0.25s ease;
624
+ }
625
+ .loading-overlay.active { opacity: 1; pointer-events: all; }
626
+
627
+ .no-data-msg {
628
+ text-align: center;
629
+ padding: 3rem;
630
+ color: var(--text-dark);
631
+ font-weight: 500;
632
+ }
633
+ .no-data-msg i {
634
+ font-size: 2.5rem;
635
+ margin-bottom: 0.75rem;
636
+ display: block;
637
+ opacity: 0.5;
638
+ }
639
+
640
+ /* Modal Dialog systems (.modal-overlay/.modal-box/.modal-title base: ui/app.css, #164) */
641
+ .modal-overlay {
642
+ width: 100%; height: 100%;
643
+ }
644
+ .modal-overlay.open {
645
+ display: flex;
646
+ }
647
+
648
+ .modal-close-btn {
649
+ position: absolute;
650
+ top: 1.25rem;
651
+ right: 1.25rem;
652
+ background: none;
653
+ border: none;
654
+ color: var(--text-dark);
655
+ cursor: pointer;
656
+ font-size: 1.2rem;
657
+ transition: var(--transition-smooth);
658
+ }
659
+ .modal-close-btn:hover {
660
+ color: var(--text-main);
661
+ }
662
+
663
+ .modal-title {
664
+ margin-bottom: 1.5rem;
665
+ color: #fff;
666
+ }
667
+
668
+ .form-group {
669
+ margin-bottom: 1.25rem;
670
+ display: flex;
671
+ flex-direction: column;
672
+ gap: 0.5rem;
673
+ }
674
+
675
+ /* .form-group label / .form-control base: ui/app.css (#164) */
676
+ .form-control {
677
+ outline: none;
678
+ box-sizing: border-box;
679
+ }
680
+
681
+ /* Dark datepicker input custom style overrides */
682
+ input[type="date"] {
683
+ color-scheme: dark;
684
+ }
685
+ input[type="date"]::-webkit-calendar-picker-indicator {
686
+ filter: invert(0.9) sepia(1) saturate(5) hue-rotate(240deg);
687
+ cursor: pointer;
688
+ }
689
+
690
+ /* Custom Flatpickr styling overrides to match theme */
691
+ .flatpickr-calendar {
692
+ background: #111322 !important;
693
+ border: 1px solid var(--panel-border) !important;
694
+ box-shadow: 0 10px 25px rgba(0,0,0,0.6) !important;
695
+ font-family: var(--font-family) !important;
696
+ border-radius: 12px !important;
697
+ }
698
+ .flatpickr-day.selected,
699
+ .flatpickr-day.startRange,
700
+ .flatpickr-day.endRange,
701
+ .flatpickr-day.selected.inRange,
702
+ .flatpickr-day.startRange.inRange,
703
+ .flatpickr-day.endRange.inRange,
704
+ .flatpickr-day.selected:focus,
705
+ .flatpickr-day.startRange:focus,
706
+ .flatpickr-day.endRange:focus,
707
+ .flatpickr-day.selected:hover,
708
+ .flatpickr-day.startRange:hover,
709
+ .flatpickr-day.endRange:hover,
710
+ .flatpickr-day.prevMonthDay.selected,
711
+ .flatpickr-day.nextMonthDay.selected {
712
+ background: var(--accent-primary) !important;
713
+ border-color: var(--accent-primary) !important;
714
+ }
715
+ .flatpickr-months .flatpickr-month {
716
+ color: #fff !important;
717
+ }
718
+ .flatpickr-current-month .flatpickr-monthDropdown-months {
719
+ background: #111322 !important;
720
+ color: #fff !important;
721
+ }
722
+ .flatpickr-day {
723
+ color: var(--text-main) !important;
724
+ }
725
+ .flatpickr-day:hover {
726
+ background: rgba(255, 255, 255, 0.08) !important;
727
+ }
728
+ .flatpickr-day.flatpickr-disabled,
729
+ .flatpickr-day.flatpickr-disabled:hover {
730
+ color: var(--text-dark) !important;
731
+ background: transparent !important;
732
+ }
733
+ .flatpickr-weekday {
734
+ color: var(--text-muted) !important;
735
+ }
736
+ .flatpickr-months .flatpickr-prev-month, .flatpickr-months .flatpickr-next-month {
737
+ color: var(--text-muted) !important;
738
+ fill: var(--text-muted) !important;
739
+ }
740
+ .flatpickr-calendar.arrowTop:before, .flatpickr-calendar.arrowTop:after {
741
+ border-bottom-color: #111322 !important;
742
+ }
743
+ .flatpickr-calendar.arrowBottom:before, .flatpickr-calendar.arrowBottom:after {
744
+ border-top-color: #111322 !important;
745
+ }
746
+
747
+ /* Hide HTML5 Up/Down Spin-Buttons */
748
+ input::-webkit-outer-spin-button,
749
+ input::-webkit-inner-spin-button {
750
+ -webkit-appearance: none;
751
+ margin: 0;
752
+ }
753
+ input[type=number] {
754
+ -moz-appearance: textfield;
755
+ }
756
+
757
+ .modal-footer {
758
+ display: flex;
759
+ justify-content: flex-end;
760
+ gap: 0.75rem;
761
+ margin-top: 1.5rem;
762
+ }
763
+
764
+ /* Toast system (.toast-container/.toast base: ui/app.css, #164) */
765
+ .toast {
766
+ color: var(--text-main);
767
+ border-left: 4px solid var(--accent-primary);
768
+ backdrop-filter: blur(12px);
769
+ min-width: 300px;
770
+ animation: slideIn 0.35s cubic-bezier(0.175, 0.885, 0.32, 1.275) forwards;
771
+ position: relative;
772
+ }
773
+ .toast.success { border-left-color: var(--income-color); }
774
+ .toast.error { border-left-color: var(--expense-color); }
775
+
776
+ .toast-close {
777
+ position: absolute; right: 10px; top: 50%;
778
+ transform: translateY(-50%);
779
+ color: var(--text-dark); cursor: pointer; font-size: 0.8rem;
780
+ }
781
+ .toast-close:hover { color: var(--text-main); }
782
+
783
+ @keyframes slideIn {
784
+ from { transform: translateX(100%); opacity: 0; }
785
+ to { transform: translateX(0); opacity: 1; }
786
+ }
787
+ @keyframes fadeOut {
788
+ to { opacity: 0; transform: translateY(20px); }
789
+ }
790
+
791
+ /* Top workspace layout grid */
792
+ .top-workspace-grid {
793
+ display: grid;
794
+ grid-template-columns: 1.8fr 1.2fr;
795
+ gap: 1.5rem;
796
+ margin-bottom: 1rem;
797
+ align-items: stretch;
798
+ }
799
+ @media (max-width: 1024px) {
800
+ .top-workspace-grid {
801
+ grid-template-columns: 1fr;
802
+ }
803
+ }
804
+
805
+ /* Compact Bill Panel inside top workspace grid */
806
+ .compact-bill-panel {
807
+ padding: 1.25rem 1.5rem !important;
808
+ border-radius: 20px !important;
809
+ display: flex !important;
810
+ flex-direction: column !important;
811
+ gap: 0.75rem !important;
812
+ background: var(--panel-bg) !important;
813
+ border: 1px solid var(--panel-border) !important;
814
+ box-sizing: border-box !important;
815
+ height: 100% !important;
816
+ justify-content: space-between !important;
817
+ }
818
+
819
+ .compact-bill-header {
820
+ display: flex !important;
821
+ justify-content: center !important;
822
+ align-items: center !important;
823
+ flex-wrap: wrap !important;
824
+ gap: 0.5rem !important;
825
+ border-bottom: none !important;
826
+ padding-bottom: 0 !important;
827
+ }
828
+
829
+ .compact-bill-title {
830
+ display: flex !important;
831
+ align-items: center !important;
832
+ gap: 0.5rem !important;
833
+ font-size: 1rem !important;
834
+ font-weight: 600 !important;
835
+ color: var(--text-main) !important;
836
+ margin-bottom: 0 !important;
837
+ }
838
+
839
+ .compact-bill-info-box {
840
+ display: flex !important;
841
+ flex-direction: row !important;
842
+ justify-content: space-between !important;
843
+ align-items: center !important;
844
+ gap: 1.25rem !important;
845
+ background: rgba(0, 0, 0, 0.15) !important;
846
+ border: 1px solid var(--panel-border) !important;
847
+ border-radius: 16px !important;
848
+ padding: 1.25rem !important;
849
+ flex-wrap: wrap !important;
850
+ flex: 1 !important;
851
+ margin-bottom: 0.5rem !important;
852
+ }
853
+
854
+ .compact-bill-row {
855
+ display: flex !important;
856
+ flex-direction: column !important;
857
+ align-items: flex-start !important;
858
+ justify-content: center !important;
859
+ gap: 4px !important;
860
+ flex: 1 !important;
861
+ min-width: 75px !important;
862
+ }
863
+
864
+ .compact-bill-row.total-area {
865
+ flex: 1 1 100% !important;
866
+ align-items: center !important;
867
+ justify-content: center !important;
868
+ border-left: none !important;
869
+ border-top: 1px dashed var(--panel-border) !important;
870
+ padding-top: 1rem !important;
871
+ padding-left: 0 !important;
872
+ margin-top: 0.75rem !important;
873
+ width: 100% !important;
874
+ }
875
+
876
+ .compact-bill-label {
877
+ font-size: 0.7rem !important;
878
+ color: var(--text-muted) !important;
879
+ text-transform: uppercase !important;
880
+ letter-spacing: 0.05em !important;
881
+ margin-bottom: 0 !important;
882
+ }
883
+
884
+ .compact-bill-value {
885
+ font-weight: 600 !important;
886
+ font-size: 0.85rem !important;
887
+ color: var(--text-main) !important;
888
+ }
889
+
890
+ .compact-bill-total-amount {
891
+ font-size: 1.25rem !important;
892
+ font-weight: 700 !important;
893
+ color: var(--text-main) !important;
894
+ margin-top: 0 !important;
895
+ }
896
+
897
+ .compact-bill-actions {
898
+ display: flex !important;
899
+ gap: 0.75rem !important;
900
+ width: 100% !important;
901
+ margin-top: 0 !important;
902
+ }
903
+
904
+ /* Premium Transaction List styles */
905
+ .tx-list-container {
906
+ display: flex;
907
+ flex-direction: column;
908
+ gap: 1.25rem;
909
+ width: 100%;
910
+ }
911
+
912
+ .day-group {
913
+ display: flex;
914
+ flex-direction: column;
915
+ gap: 0.5rem;
916
+ width: 100%;
917
+ }
918
+
919
+ .day-group-header {
920
+ display: flex;
921
+ justify-content: space-between;
922
+ align-items: center;
923
+ padding: 0.5rem 0.75rem;
924
+ border-bottom: 1px solid rgba(255, 255, 255, 0.05);
925
+ font-size: 0.8rem;
926
+ text-transform: uppercase;
927
+ letter-spacing: 0.05em;
928
+ width: 100%;
929
+ box-sizing: border-box;
930
+ }
931
+
932
+ .day-group-date {
933
+ color: var(--accent-primary);
934
+ font-weight: 700;
935
+ display: flex;
936
+ align-items: center;
937
+ gap: 0.5rem;
938
+ }
939
+
940
+ .day-group-summary {
941
+ color: var(--text-muted);
942
+ font-weight: 600;
943
+ }
944
+
945
+ .day-group-sum-val {
946
+ color: var(--text-main);
947
+ font-weight: 700;
948
+ }
949
+
950
+ .day-group-items {
951
+ display: flex;
952
+ flex-direction: column;
953
+ gap: 0.5rem;
954
+ }
955
+
956
+ .tx-list-item {
957
+ display: flex;
958
+ flex-direction: column;
959
+ background: rgba(255, 255, 255, 0.015);
960
+ border: 1px solid rgba(255, 255, 255, 0.03);
961
+ border-radius: 12px;
962
+ transition: var(--transition-smooth);
963
+ overflow: hidden;
964
+ }
965
+
966
+ .tx-list-item.has-note {
967
+ cursor: pointer;
968
+ }
969
+
970
+ .tx-list-item:hover {
971
+ background: rgba(255, 255, 255, 0.035);
972
+ border-color: rgba(255, 255, 255, 0.08);
973
+ transform: translateY(-1px);
974
+ }
975
+
976
+ .tx-item-row-content {
977
+ display: flex;
978
+ align-items: center;
979
+ justify-content: space-between;
980
+ padding: 0.75rem 1rem;
981
+ width: 100%;
982
+ box-sizing: border-box;
983
+ }
984
+
985
+ .tx-item-left {
986
+ display: flex;
987
+ align-items: center;
988
+ gap: 0.85rem;
989
+ width: 50%;
990
+ flex-shrink: 0;
991
+ min-width: 0;
992
+ }
993
+
994
+ .tx-item-icon {
995
+ width: 38px;
996
+ height: 38px;
997
+ border-radius: 10px;
998
+ display: flex;
999
+ align-items: center;
1000
+ justify-content: center;
1001
+ font-size: 1rem;
1002
+ flex-shrink: 0;
1003
+ border: 1px solid rgba(255, 255, 255, 0.08);
1004
+ }
1005
+
1006
+ .tx-item-details {
1007
+ display: flex;
1008
+ flex-direction: column;
1009
+ gap: 2px;
1010
+ min-width: 0;
1011
+ flex: 1;
1012
+ }
1013
+
1014
+ .tx-item-desc {
1015
+ font-weight: 500;
1016
+ color: var(--text-main);
1017
+ font-size: 0.95rem;
1018
+ white-space: nowrap;
1019
+ overflow: hidden;
1020
+ text-overflow: ellipsis;
1021
+ }
1022
+
1023
+ .tx-item-meta {
1024
+ display: flex;
1025
+ align-items: center;
1026
+ gap: 0.5rem;
1027
+ flex-wrap: wrap;
1028
+ }
1029
+
1030
+ .tx-item-note {
1031
+ font-size: 0.75rem;
1032
+ color: var(--text-muted);
1033
+ font-style: italic;
1034
+ }
1035
+
1036
+ .tx-item-right {
1037
+ display: flex;
1038
+ align-items: center;
1039
+ justify-content: flex-end;
1040
+ gap: 1.25rem;
1041
+ flex: 1;
1042
+ min-width: 0;
1043
+ }
1044
+
1045
+ .tx-item-drawer {
1046
+ max-height: 0;
1047
+ overflow: hidden;
1048
+ transition: max-height 0.25s ease-out;
1049
+ background: rgba(0, 0, 0, 0.15);
1050
+ }
1051
+
1052
+ .tx-list-item.expanded .tx-item-drawer {
1053
+ max-height: 100px;
1054
+ }
1055
+
1056
+ .tx-item-drawer-inner {
1057
+ padding: 0.75rem 1rem 0.75rem 3.8rem;
1058
+ border-top: 1px solid rgba(255, 255, 255, 0.04);
1059
+ font-size: 0.85rem;
1060
+ color: var(--text-muted);
1061
+ line-height: 1.4;
1062
+ display: flex;
1063
+ align-items: flex-start;
1064
+ }
1065
+
1066
+ .tx-item-amount {
1067
+ font-weight: 700;
1068
+ font-size: 1.05rem;
1069
+ white-space: nowrap;
1070
+ }
1071
+ .tx-item-amount.expense {
1072
+ color: var(--expense-color);
1073
+ }
1074
+ .tx-item-amount.income {
1075
+ color: var(--income-color);
1076
+ }
1077
+
1078
+ .sort-controls {
1079
+ display: flex;
1080
+ align-items: center;
1081
+ gap: 0.5rem;
1082
+ font-size: 0.75rem;
1083
+ color: var(--text-muted);
1084
+ }
1085
+
1086
+ .sort-link {
1087
+ transition: var(--transition-smooth);
1088
+ cursor: pointer;
1089
+ }
1090
+
1091
+ .sort-link:hover {
1092
+ color: var(--accent-primary);
1093
+ }
1094
+
1095
+ .sort-link.active {
1096
+ color: var(--accent-primary);
1097
+ font-weight: 700;
1098
+ }
1099
+
1100
+ /* Custom Select component styling */
1101
+ .select-container-custom {
1102
+ position: relative;
1103
+ display: inline-block;
1104
+ min-width: 120px;
1105
+ user-select: none;
1106
+ }
1107
+
1108
+ .select-trigger-custom {
1109
+ background: rgba(255, 255, 255, 0.05);
1110
+ border: 1px solid var(--panel-border);
1111
+ color: var(--text-main);
1112
+ padding: 0.5rem 2.2rem 0.5rem 0.75rem;
1113
+ border-radius: 8px;
1114
+ cursor: pointer;
1115
+ font-size: 0.85rem;
1116
+ font-weight: 600;
1117
+ display: flex;
1118
+ align-items: center;
1119
+ justify-content: space-between;
1120
+ transition: var(--transition-smooth);
1121
+ min-height: 36px;
1122
+ box-sizing: border-box;
1123
+ }
1124
+
1125
+ .select-trigger-custom:hover {
1126
+ border-color: rgba(255, 255, 255, 0.15);
1127
+ background: rgba(255, 255, 255, 0.08);
1128
+ }
1129
+
1130
+ .select-container-custom.open .select-trigger-custom {
1131
+ border-color: var(--accent-primary);
1132
+ box-shadow: 0 0 0 2px var(--accent-primary-glow);
1133
+ }
1134
+
1135
+ .select-trigger-custom::after {
1136
+ content: '\f078';
1137
+ font-family: 'Font Awesome 6 Free';
1138
+ font-weight: 900;
1139
+ font-size: 0.7rem;
1140
+ color: var(--text-muted);
1141
+ position: absolute;
1142
+ right: 12px;
1143
+ transition: transform 0.3s ease;
1144
+ }
1145
+
1146
+ .select-container-custom.open .select-trigger-custom::after {
1147
+ transform: rotate(180deg);
1148
+ color: var(--accent-primary);
1149
+ }
1150
+
1151
+ .select-options-custom {
1152
+ display: none;
1153
+ position: absolute;
1154
+ top: calc(100% + 6px);
1155
+ left: 0;
1156
+ width: 100%;
1157
+ background: rgba(22, 22, 34, 0.98); /* Opaque dark background to prevent bleed-through */
1158
+ border: 1px solid var(--panel-border);
1159
+ border-radius: 12px;
1160
+ box-shadow: 0 10px 25px rgba(0, 0, 0, 0.6);
1161
+ z-index: 1000;
1162
+ max-height: 250px;
1163
+ overflow-y: auto;
1164
+ padding: 4px;
1165
+ backdrop-filter: blur(20px);
1166
+ box-sizing: border-box;
1167
+ animation: selectFadeIn 0.2s cubic-bezier(0.16, 1, 0.3, 1);
1168
+ }
1169
+
1170
+ @keyframes selectFadeIn {
1171
+ from { opacity: 0; transform: translateY(-8px); }
1172
+ to { opacity: 1; transform: translateY(0); }
1173
+ }
1174
+
1175
+ .select-container-custom.open .select-options-custom {
1176
+ display: block;
1177
+ }
1178
+
1179
+ .select-option-custom {
1180
+ padding: 0.5rem 0.75rem;
1181
+ color: var(--text-muted); /* Highly readable text color on dark backgrounds */
1182
+ font-size: 0.82rem;
1183
+ font-weight: 500;
1184
+ border-radius: 6px;
1185
+ cursor: pointer;
1186
+ transition: var(--transition-smooth);
1187
+ }
1188
+
1189
+ .select-option-custom:hover {
1190
+ background: rgba(255, 255, 255, 0.08);
1191
+ color: #fff;
1192
+ }
1193
+
1194
+ .select-option-custom.selected {
1195
+ background: var(--accent-primary-glow);
1196
+ color: var(--accent-primary);
1197
+ font-weight: 700;
1198
+ }
1199
+
1200
+ .select-options-custom::-webkit-scrollbar {
1201
+ width: 6px;
1202
+ }
1203
+ .select-options-custom::-webkit-scrollbar-track {
1204
+ background: transparent;
1205
+ }
1206
+ .select-options-custom::-webkit-scrollbar-thumb {
1207
+ background: rgba(255, 255, 255, 0.1);
1208
+ border-radius: 3px;
1209
+ }
1210
+ </style>
1211
+
1212
+ <div class="dashboard-container">
1213
+ <!-- Header -->
1214
+ <header>
1215
+ <div class="header-title-area">
1216
+ <h1><i class="fa-solid fa-credit-card"></i> Cartões & Faturas</h1>
1217
+ <p>Monitore limites, analise extratos e realize pagamentos de faturas</p>
1218
+ </div>
1219
+ <div class="controls-area">
1220
+ <label for="month-select" data-i18n="reference_label">Reference:</label>
1221
+ <select id="month-select" class="select-custom">
1222
+ <option value="1">Janeiro</option>
1223
+ <option value="2">Fevereiro</option>
1224
+ <option value="3">Março</option>
1225
+ <option value="4">Abril</option>
1226
+ <option value="5">Maio</option>
1227
+ <option value="6">Junho</option>
1228
+ <option value="7" selected>Julho</option>
1229
+ <option value="8">Agosto</option>
1230
+ <option value="9">Setembro</option>
1231
+ <option value="10">Outubro</option>
1232
+ <option value="11">Novembro</option>
1233
+ <option value="12">Dezembro</option>
1234
+ </select>
1235
+ <select id="year-select" class="select-custom">
1236
+ <option value="2025">2025</option>
1237
+ <option value="2026" selected>2026</option>
1238
+ <option value="2027">2027</option>
1239
+ </select>
1240
+ </div>
1241
+ </header>
1242
+
1243
+ <!-- Wrapper to keep title and workspace grid close together -->
1244
+ <div style="display: flex; flex-direction: column;">
1245
+ <!-- Section Header above top-workspace-grid -->
1246
+ <div class="section-title" style="display:flex; justify-content: space-between; align-items: center; width: 100%; margin-bottom: 0.5rem;">
1247
+ <div style="display:flex; align-items: center; gap: 0.5rem;">
1248
+ <i class="fa-solid fa-wallet"></i>
1249
+ <span>Selecione um Cartão de Crédito</span>
1250
+ </div>
1251
+ <div style="display:flex; gap: 0.5rem;">
1252
+ <button class="btn-mini-add" id="btn-edit-card" onclick="openEditCardModal()" style="background: rgba(255,255,255,0.05); border: 1px solid var(--panel-border); color: #fff; display: none;">
1253
+ <i class="fa-solid fa-pen-to-square"></i> <span data-i18n="btn_edit_card">Editar Cartão</span>
1254
+ </button>
1255
+ <button class="btn-mini-add" onclick="openAddCardModal()">
1256
+ <i class="fa-solid fa-plus"></i> <span data-i18n="new_card">Novo Cartão</span>
1257
+ </button>
1258
+ </div>
1259
+ </div>
1260
+
1261
+ <!-- Top Workspace: Cards Selector & Bill Cycle Info -->
1262
+ <div class="top-workspace-grid" style="margin-bottom: 0.75rem;">
1263
+ <!-- Left Column: Cards carousel -->
1264
+ <div class="cards-carousel" id="cards-container" style="margin-top: 0;">
1265
+ <!-- Loaded dynamically -->
1266
+ </div>
1267
+
1268
+ <!-- Right Column: Bill summary and details (Ciclo & Fatura) -->
1269
+ <section class="compact-bill-panel" style="position: relative;">
1270
+ <div class="loading-overlay" id="bill-loading">
1271
+ <div class="spinner"></div>
1272
+ </div>
1273
+
1274
+ <div class="compact-bill-header" style="display: flex; flex-direction: column; align-items: center; gap: 0.5rem; width: 100%;">
1275
+ <div class="compact-bill-title" style="justify-content: center; font-size: 1.1rem; margin-bottom: 0.25rem;">
1276
+ <i class="fa-solid fa-receipt"></i>
1277
+ <span>Ciclo & Fatura</span>
1278
+ </div>
1279
+ <!-- Past / Current / Future Tabs (Centered below title) -->
1280
+ <div class="bill-cycle-tabs" id="bill-tabs" style="margin: 0 auto; width: 100%; max-width: 320px; padding: 2px; gap: 2px; display: flex; justify-content: center;">
1281
+ <button class="bill-tab" id="tab-past" onclick="selectBillType('past')" style="padding: 0.35rem 0.65rem; font-size: 0.75rem; border-radius: 6px; flex: 1;">Passada</button>
1282
+ <button class="bill-tab active" id="tab-current" onclick="selectBillType('current')" style="padding: 0.35rem 0.65rem; font-size: 0.75rem; border-radius: 6px; flex: 1;">Atual</button>
1283
+ <button class="bill-tab" id="tab-future" onclick="selectBillType('future')" style="padding: 0.35rem 0.65rem; font-size: 0.75rem; border-radius: 6px; flex: 1;">Futura</button>
1284
+ </div>
1285
+ </div>
1286
+
1287
+ <!-- Bill Details row (Flexed horizontally!) -->
1288
+ <div class="compact-bill-info-box">
1289
+ <div class="compact-bill-row">
1290
+ <span class="compact-bill-label">Status</span>
1291
+ <span class="bill-status-badge open" id="bill-status-badge" style="align-self: flex-start; font-size: 0.7rem; padding: 2px 6px;">Aberta</span>
1292
+ </div>
1293
+ <div class="compact-bill-row">
1294
+ <span class="compact-bill-label">Fechamento</span>
1295
+ <span class="compact-bill-value" id="bill-close-date">-</span>
1296
+ </div>
1297
+ <div class="compact-bill-row">
1298
+ <span class="compact-bill-label">Vencimento</span>
1299
+ <span class="compact-bill-value" id="bill-due-date">-</span>
1300
+ </div>
1301
+ <div class="compact-bill-row total-area">
1302
+ <span class="compact-bill-label" id="bill-total-label">Total da Fatura</span>
1303
+ <span class="compact-bill-total-amount" id="bill-total-val">—</span>
1304
+ </div>
1305
+ </div>
1306
+
1307
+ <!-- Bill Actions -->
1308
+ <div class="compact-bill-actions">
1309
+ <button class="btn-action-primary" id="btn-pay-bill" onclick="openPayModal()" style="padding: 0.45rem 1rem; font-size: 0.8rem; flex: 1;">
1310
+ <i class="fa-solid fa-money-bill-transfer"></i> Pagar Fatura
1311
+ </button>
1312
+ <button class="btn-action-secondary" id="btn-revert-pay" onclick="revertBillPayment()" style="display: none; padding: 0.45rem 1rem; font-size: 0.8rem; flex: 1;">
1313
+ <i class="fa-solid fa-undo"></i> Reverter
1314
+ </button>
1315
+ </div>
1316
+ </section>
1317
+ </div>
1318
+ </div>
1319
+
1320
+ <!-- Bottom Panel: Transaction list for the bill (Full Width) -->
1321
+ <section class="panel" style="position: relative; width: 100%; box-sizing: border-box; padding: 1.5rem;">
1322
+ <div class="loading-overlay" id="tx-loading">
1323
+ <div class="spinner"></div>
1324
+ </div>
1325
+
1326
+ <div class="panel-header" style="justify-content: space-between; display: flex; align-items: center; margin-bottom: 1.25rem; flex-wrap: wrap; gap: 0.75rem; border-bottom: none; padding-bottom: 0;">
1327
+ <div class="panel-title" style="margin-bottom: 0;">
1328
+ <i class="fa-solid fa-list-ul"></i>
1329
+ <span>Lançamentos Vinculados</span>
1330
+ </div>
1331
+ <div class="panel-header-buttons" style="display: flex; align-items: center; gap: 1rem; flex-wrap: wrap;">
1332
+ <!-- Sort controls inside header -->
1333
+ <div class="sort-controls">
1334
+ <span>Ordenar:</span>
1335
+ <span class="sort-link active" onclick="toggleSort('date')" id="sort-link-date">Data</span>
1336
+ <span>•</span>
1337
+ <span class="sort-link" onclick="toggleSort('description')" id="sort-link-description">Descrição</span>
1338
+ <span>•</span>
1339
+ <span class="sort-link" onclick="toggleSort('category')" id="sort-link-category">Categoria</span>
1340
+ <span>•</span>
1341
+ <span class="sort-link" onclick="toggleSort('amount')" id="sort-link-amount">Valor</span>
1342
+ </div>
1343
+ <button class="btn-mini-add" onclick="openAddTxModal()">
1344
+ <i class="fa-solid fa-plus"></i> Novo Lançamento
1345
+ </button>
1346
+ </div>
1347
+ </div>
1348
+
1349
+ <!-- Wide Search Box Row -->
1350
+ <div class="tx-filter-row" style="margin-bottom: 1.25rem; width: 100%;">
1351
+ <div class="search-box-wrapper" style="position: relative; display: flex; align-items: center; width: 100%;">
1352
+ <i class="fa-solid fa-magnifying-glass" style="position: absolute; left: 12px; color: var(--text-muted); font-size: 0.9rem; pointer-events: none;"></i>
1353
+ <input type="text" id="tx-search-input" placeholder="Buscar por descrição, categoria, tags ou observações..." oninput="handleTxSearch(this.value)" style="background: rgba(255, 255, 255, 0.04); border: 1px solid rgba(255, 255, 255, 0.08); border-radius: 10px; padding: 0.5rem 1rem 0.5rem 2.5rem; color: var(--text-main); font-size: 0.85rem; width: 100%; box-sizing: border-box; transition: all 0.25s ease; outline: none;" onfocus="this.style.borderColor='var(--accent-primary)'; this.style.background='rgba(255, 255, 255, 0.07)'; this.style.boxShadow='0 0 0 3px rgba(139, 92, 246, 0.15)';" onblur="this.style.borderColor='rgba(255, 255, 255, 0.08)'; this.style.background='rgba(255, 255, 255, 0.04)'; this.style.boxShadow='none';">
1354
+ </div>
1355
+ </div>
1356
+
1357
+ <!-- List-based Statement instead of table -->
1358
+ <div class="tx-list-container" id="bill-txs-list">
1359
+ <!-- Populated dynamically -->
1360
+ </div>
1361
+ <div id="no-tx-msg" class="no-data-msg" style="display: none;">
1362
+ <i class="fa-regular fa-folder-open"></i>
1363
+ Nenhum lançamento encontrado para esta fatura.
1364
+ </div>
1365
+ </section>
1366
+ </div>
1367
+
1368
+ <!-- MODAL: ADD TRANSACTION -->
1369
+ <div class="modal-overlay" id="modal-add-tx">
1370
+ <div class="modal-box split-modal">
1371
+ <button class="modal-close-btn" onclick="closeModal('modal-add-tx')"><i class="fa-solid fa-xmark"></i></button>
1372
+ <div class="modal-title">
1373
+ <i class="fa-solid fa-circle-plus"></i>
1374
+ <span>Novo Lançamento</span>
1375
+ </div>
1376
+ <form id="form-add-tx" onsubmit="handleAddTxSubmit(event)">
1377
+ <div class="modal-split-body">
1378
+ <!-- Left Column: Fields -->
1379
+ <div class="modal-column-left">
1380
+ <div class="form-group">
1381
+ <label for="add-desc">Descrição</label>
1382
+ <input type="text" id="add-desc" class="form-control" placeholder="Ex: Supermercado" required>
1383
+ </div>
1384
+ <div class="form-group" style="display:grid; grid-template-columns: 1fr 1fr; gap:0.75rem;">
1385
+ <div>
1386
+ <label for="add-amount">Valor</label>
1387
+ <input type="number" step="0.01" min="0.01" id="add-amount" class="form-control" placeholder="0,00" required>
1388
+ </div>
1389
+ <div>
1390
+ <label for="add-date">Data</label>
1391
+ <input type="date" id="add-date" class="form-control" required>
1392
+ </div>
1393
+ </div>
1394
+ <div class="form-group">
1395
+ <label for="add-category">Categoria</label>
1396
+ <select id="add-category" class="form-control select-custom" style="background-image:none; padding-right:0.75rem;" required>
1397
+ <!-- Populated dynamically -->
1398
+ </select>
1399
+ </div>
1400
+ <div class="form-group">
1401
+ <label for="add-bill-cycle">Fatura de Destino</label>
1402
+ <select id="add-bill-cycle" class="form-control select-custom" style="background-image:none; padding-right:0.75rem;">
1403
+ <option value="auto">Automática (Baseada na data)</option>
1404
+ <!-- Populated dynamically -->
1405
+ </select>
1406
+ </div>
1407
+ </div>
1408
+
1409
+ <!-- Right Column: Observações & Tags -->
1410
+ <div class="modal-column-right">
1411
+ <div class="form-group" style="display:flex; flex-direction:column; margin-bottom: 0.75rem;">
1412
+ <label for="add-note">Observação / Notas da Transação</label>
1413
+ <textarea id="add-note" class="textarea-large" placeholder="Escreva observações sobre este lançamento..." style="min-height: 120px; flex: 1;"></textarea>
1414
+ </div>
1415
+ <div class="form-group">
1416
+ <label for="add-tags">Tags (separadas por vírgula)</label>
1417
+ <input type="text" id="add-tags" class="form-control" placeholder="ex: viagem, mercado, lazer">
1418
+ </div>
1419
+ </div>
1420
+ </div>
1421
+ <div class="modal-footer">
1422
+ <button type="button" class="btn-action-secondary" onclick="closeModal('modal-add-tx')" style="width:auto;">Cancelar</button>
1423
+ <button type="submit" class="btn-action-primary" style="width:auto;">Adicionar</button>
1424
+ </div>
1425
+ </form>
1426
+ </div>
1427
+ </div>
1428
+ <!-- MODAL: ADD CREDIT CARD -->
1429
+ <div class="modal-overlay" id="modal-add-card">
1430
+ <div class="modal-box split-modal">
1431
+ <button class="modal-close-btn" onclick="closeModal('modal-add-card')"><i class="fa-solid fa-xmark"></i></button>
1432
+ <div class="modal-title">
1433
+ <i class="fa-solid fa-credit-card"></i>
1434
+ <span data-i18n="modal_add_card_title">Novo Cartão de Crédito</span>
1435
+ </div>
1436
+ <form id="form-add-card" onsubmit="handleAddCardSubmit(event)">
1437
+ <div class="modal-split-body">
1438
+ <!-- Left Column: Fields -->
1439
+ <div class="modal-column-left">
1440
+ <div class="form-group">
1441
+ <label for="card-add-name" data-i18n="label_card_name">Nome do Cartão</label>
1442
+ <input type="text" id="card-add-name" class="form-control" placeholder="Ex: Nu Ultravioleta" oninput="updateCardPreview()" required>
1443
+ </div>
1444
+ <div class="form-group">
1445
+ <label for="card-add-limit" data-i18n="label_limit">Limite</label>
1446
+ <input type="number" step="0.01" min="1" id="card-add-limit" class="form-control" placeholder="0,00" oninput="updateCardPreview()" required>
1447
+ </div>
1448
+ <div style="display:grid; grid-template-columns: 1fr 1.8fr; gap:0.75rem; margin-bottom: 1.25rem;">
1449
+ <div class="form-group" style="margin-bottom:0;">
1450
+ <label for="card-add-closing-day" data-i18n="label_closing_day">Fechamento</label>
1451
+ <input type="number" min="1" max="28" id="card-add-closing-day" class="form-control" placeholder="ex: 5" style="max-width: 90px;" required>
1452
+ </div>
1453
+ <div class="form-group" style="margin-bottom:0;">
1454
+ <label for="card-add-due-day" data-i18n="label_due_day">Vencimento</label>
1455
+ <input type="number" min="1" max="28" id="card-add-due-day" class="form-control" placeholder="ex: 15" style="max-width: 90px;" required>
1456
+ </div>
1457
+ </div>
1458
+ <div style="display:grid; grid-template-columns: 1fr 1.8fr; gap:0.75rem; margin-bottom: 1.25rem;">
1459
+ <div class="form-group" style="margin-bottom:0;">
1460
+ <label for="card-add-currency" data-i18n="label_currency">Moeda</label>
1461
+ <select id="card-add-currency" class="form-control select-custom" onchange="updateCardPreview()">
1462
+ <!-- Populated from the currency metadata -->
1463
+ </select>
1464
+ </div>
1465
+ <div class="form-group" style="margin-bottom:0;">
1466
+ <label for="card-add-payment-account" data-i18n="label_payment_account">Conta Padrão</label>
1467
+ <select id="card-add-payment-account" class="form-control select-custom" style="color: var(--text-muted);">
1468
+ <!-- Populated dynamically -->
1469
+ </select>
1470
+ </div>
1471
+ </div>
1472
+ </div>
1473
+
1474
+ <!-- Right Column: Live Mockup Preview -->
1475
+ <div class="modal-column-right" style="justify-content: center; align-items: center; gap: 0.75rem;">
1476
+ <div style="font-size: 0.75rem; text-transform: uppercase; color: var(--text-muted); font-weight: 700; text-align: center;" data-i18n="design_preview">Pré-visualização do Design</div>
1477
+ <div id="card-preview-element" class="credit-card-mockup personnalite-black active" style="pointer-events: none; width: 320px; height: 190px; margin: 0; box-shadow: 0 0 25px rgba(212, 175, 55, 0.35); border-color: #d4af37;">
1478
+ <!-- Filled dynamically -->
1479
+ </div>
1480
+ </div>
1481
+ </div>
1482
+ <div class="modal-footer">
1483
+ <button type="button" class="btn-action-secondary" onclick="closeModal('modal-add-card')" style="width:auto;" data-i18n="btn_cancel">Cancelar</button>
1484
+ <button type="submit" class="btn-action-primary" style="width:auto;" data-i18n="btn_create_card">Criar Cartão</button>
1485
+ </div>
1486
+ </form>
1487
+ </div>
1488
+ </div>
1489
+
1490
+ <!-- MODAL: EDIT CREDIT CARD -->
1491
+ <div class="modal-overlay" id="modal-edit-card">
1492
+ <div class="modal-box split-modal">
1493
+ <button class="modal-close-btn" onclick="closeModal('modal-edit-card')"><i class="fa-solid fa-xmark"></i></button>
1494
+ <div class="modal-title">
1495
+ <i class="fa-solid fa-credit-card"></i>
1496
+ <span data-i18n="modal_edit_card_title">Editar Cartão de Crédito</span>
1497
+ </div>
1498
+ <form id="form-edit-card" onsubmit="handleEditCardSubmit(event)">
1499
+ <div class="modal-split-body">
1500
+ <!-- Left Column: Fields -->
1501
+ <div class="modal-column-left">
1502
+ <div class="form-group">
1503
+ <label for="card-edit-name" data-i18n="label_card_name">Nome do Cartão</label>
1504
+ <input type="text" id="card-edit-name" class="form-control" placeholder="Ex: Nu Ultravioleta" oninput="updateCardEditPreview()" required>
1505
+ </div>
1506
+ <div class="form-group">
1507
+ <label for="card-edit-limit" data-i18n="label_limit">Limite</label>
1508
+ <input type="number" step="0.01" min="1" id="card-edit-limit" class="form-control" placeholder="0,00" oninput="updateCardEditPreview()" required>
1509
+ </div>
1510
+ <div style="display:grid; grid-template-columns: 1fr 1.8fr; gap:0.75rem; margin-bottom: 1.25rem;">
1511
+ <div class="form-group" style="margin-bottom:0;">
1512
+ <label for="card-edit-closing-day" data-i18n="label_closing_day">Fechamento</label>
1513
+ <input type="number" min="1" max="28" id="card-edit-closing-day" class="form-control" placeholder="ex: 5" style="max-width: 90px;" required>
1514
+ </div>
1515
+ <div class="form-group" style="margin-bottom:0;">
1516
+ <label for="card-edit-due-day" data-i18n="label_due_day">Vencimento</label>
1517
+ <input type="number" min="1" max="28" id="card-edit-due-day" class="form-control" placeholder="ex: 15" style="max-width: 90px;" required>
1518
+ </div>
1519
+ </div>
1520
+ <div style="display:grid; grid-template-columns: 1fr 1.8fr; gap:0.75rem; margin-bottom: 1.25rem;">
1521
+ <div class="form-group" style="margin-bottom:0;">
1522
+ <label for="card-edit-currency" data-i18n="label_currency">Moeda</label>
1523
+ <select id="card-edit-currency" class="form-control" disabled style="background: rgba(255,255,255,0.02); color: var(--text-dark);">
1524
+ <!-- Populated from the currency metadata; a card's currency is fixed -->
1525
+ </select>
1526
+ </div>
1527
+ <div class="form-group" style="margin-bottom:0;">
1528
+ <label for="card-edit-payment-account" data-i18n="label_payment_account">Conta Padrão</label>
1529
+ <select id="card-edit-payment-account" class="form-control select-custom" style="color: var(--text-muted);">
1530
+ <!-- Populated dynamically -->
1531
+ </select>
1532
+ </div>
1533
+ </div>
1534
+ </div>
1535
+
1536
+ <!-- Right Column: Live Mockup Preview -->
1537
+ <div class="modal-column-right" style="justify-content: center; align-items: center; gap: 0.75rem;">
1538
+ <div style="font-size: 0.75rem; text-transform: uppercase; color: var(--text-muted); font-weight: 700; text-align: center;" data-i18n="design_preview">Pré-visualização do Design</div>
1539
+ <div id="card-edit-preview-element" class="credit-card-mockup personnalite-black active" style="pointer-events: none; width: 320px; height: 190px; margin: 0; box-shadow: 0 0 25px rgba(212, 175, 55, 0.35); border-color: #d4af37;">
1540
+ <!-- Filled dynamically -->
1541
+ </div>
1542
+ </div>
1543
+ </div>
1544
+ <div class="modal-footer">
1545
+ <button type="button" class="btn-action-secondary" onclick="closeModal('modal-edit-card')" style="width:auto;" data-i18n="btn_cancel">Cancelar</button>
1546
+ <button type="submit" class="btn-action-primary" style="width:auto;" data-i18n="btn_save">Salvar</button>
1547
+ </div>
1548
+ </form>
1549
+ </div>
1550
+ </div>
1551
+
1552
+ <!-- MODAL: REASSIGN BILL -->
1553
+ <div class="modal-overlay" id="modal-reassign">
1554
+ <div class="modal-box">
1555
+ <button class="modal-close-btn" onclick="closeModal('modal-reassign')"><i class="fa-solid fa-xmark"></i></button>
1556
+ <div class="modal-title">
1557
+ <i class="fa-solid fa-calendar-days"></i>
1558
+ <span>Mudar Fatura do Lançamento</span>
1559
+ </div>
1560
+ <form id="form-reassign" onsubmit="handleReassignSubmit(event)">
1561
+ <input type="hidden" id="reassign-tx-id">
1562
+ <div class="form-group">
1563
+ <label>Lançamento</label>
1564
+ <div id="reassign-tx-desc" style="font-weight:600; font-size:1rem; margin-bottom:0.5rem;">-</div>
1565
+ <div id="reassign-tx-details" style="font-size:0.85rem; color:var(--text-muted);">-</div>
1566
+ </div>
1567
+ <div class="form-group">
1568
+ <label for="reassign-cycle">Vincular a Fatura de</label>
1569
+ <select id="reassign-cycle" class="form-control select-custom" style="background-image:none; padding-right:0.75rem;" required>
1570
+ <!-- Populated dynamically -->
1571
+ </select>
1572
+ </div>
1573
+ <div class="modal-footer">
1574
+ <button type="button" class="btn-action-secondary" onclick="closeModal('modal-reassign')" style="width:auto;">Cancelar</button>
1575
+ <button type="submit" class="btn-action-primary" style="width:auto;">Salvar Alteração</button>
1576
+ </div>
1577
+ </form>
1578
+ </div>
1579
+ </div>
1580
+
1581
+ <!-- MODAL: PAY BILL -->
1582
+ <div class="modal-overlay" id="modal-pay-bill">
1583
+ <div class="modal-box">
1584
+ <button class="modal-close-btn" onclick="closeModal('modal-pay-bill')"><i class="fa-solid fa-xmark"></i></button>
1585
+ <div class="modal-title">
1586
+ <i class="fa-solid fa-money-bill-transfer"></i>
1587
+ <span>Pagar Fatura</span>
1588
+ </div>
1589
+ <form id="form-pay-bill" onsubmit="handlePaySubmit(event)">
1590
+ <div class="form-group">
1591
+ <label>Cartão / Fatura</label>
1592
+ <div id="pay-card-name" style="font-weight:600; font-size:1.1rem; color:#fff;">-</div>
1593
+ <div id="pay-bill-cycle" style="font-size:0.85rem; color:var(--text-muted);">-</div>
1594
+ </div>
1595
+ <div class="form-group" style="text-align:center; padding: 1rem 0; background:rgba(0,0,0,0.2); border-radius:10px; border:1px dashed var(--panel-border);">
1596
+ <label style="margin-bottom:0;">Valor Total a Pagar</label>
1597
+ <div id="pay-bill-total" style="font-size:1.8rem; font-weight:800; color:var(--income-color);">—</div>
1598
+ </div>
1599
+ <div class="form-group">
1600
+ <label for="pay-account">Débito na Conta Corrente</label>
1601
+ <select id="pay-account" class="form-control select-custom" style="background-image:none; padding-right:0.75rem;" required>
1602
+ <!-- Populated dynamically -->
1603
+ </select>
1604
+ </div>
1605
+ <div class="form-group">
1606
+ <label for="pay-date">Data do Pagamento</label>
1607
+ <input type="date" id="pay-date" class="form-control" required>
1608
+ </div>
1609
+ <div class="modal-footer">
1610
+ <button type="button" class="btn-action-secondary" onclick="closeModal('modal-pay-bill')" style="width:auto;">Cancelar</button>
1611
+ <button type="submit" class="btn-action-primary" style="width:auto;">Confirmar Pagamento</button>
1612
+ </div>
1613
+ </form>
1614
+ </div>
1615
+ </div>
1616
+
1617
+ <!-- MODAL: CONFIRM TRANSACTION -->
1618
+ <div class="modal-overlay" id="modal-confirm-tx">
1619
+ <div class="modal-box">
1620
+ <button class="modal-close-btn" onclick="closeModal('modal-confirm-tx')"><i class="fa-solid fa-xmark"></i></button>
1621
+ <div class="modal-title">
1622
+ <i class="fa-solid fa-circle-check" style="color: var(--income-color);"></i>
1623
+ <span data-i18n="modal_confirm_tx_title">Confirmar Lançamento</span>
1624
+ </div>
1625
+ <form id="form-confirm-tx" onsubmit="handleConfirmSubmit(event)">
1626
+ <input type="hidden" id="confirm-tx-id">
1627
+ <div class="form-group">
1628
+ <label data-i18n="label_description">Lançamento</label>
1629
+ <div id="confirm-tx-desc" style="font-weight:600; font-size:1.1rem; color:#fff;">-</div>
1630
+ </div>
1631
+ <div class="form-group">
1632
+ <label for="confirm-tx-date" data-i18n="label_confirm_date">Data da Confirmação</label>
1633
+ <input type="date" id="confirm-tx-date" class="form-control" required>
1634
+ </div>
1635
+ <div class="form-group">
1636
+ <label for="confirm-tx-amount" data-i18n="label_value">Valor</label>
1637
+ <input type="number" id="confirm-tx-amount" step="0.01" min="0.01" class="form-control" required>
1638
+ </div>
1639
+ <div class="modal-footer">
1640
+ <button type="button" class="btn-action-secondary" onclick="closeModal('modal-confirm-tx')" style="width:auto;" data-i18n="btn_cancel">Cancelar</button>
1641
+ <button type="submit" class="btn-action-primary" style="width:auto;" data-i18n="btn_confirm">Confirmar</button>
1642
+ </div>
1643
+ </form>
1644
+ </div>
1645
+ </div>
1646
+
1647
+ <!-- Toast Container -->
1648
+ <div class="toast-container" id="toast-box"></div>
1649
+
1650
+
1651
+
1652
+ <script>
1653
+ // State
1654
+ var creditCards = [];
1655
+ var activeCard = null; // Card Object
1656
+ var selectedBillType = 'current'; // 'past' | 'current' | 'future'
1657
+ var currentBill = null; // Bill response object
1658
+ var accounts = [];
1659
+ var categories = [];
1660
+
1661
+ // Sorting state
1662
+ var sortColumn = 'date';
1663
+ var sortDirection = 'desc';
1664
+ var searchTerm = '';
1665
+
1666
+ // Elements
1667
+ var monthSelect = document.getElementById('month-select');
1668
+ var yearSelect = document.getElementById('year-select');
1669
+ var cardsContainer = document.getElementById('cards-container');
1670
+ var txListContainer = document.getElementById('bill-txs-list');
1671
+ var noTxMsg = document.getElementById('no-tx-msg');
1672
+ var billStatusBadge = document.getElementById('bill-status-badge');
1673
+ var billCloseDate = document.getElementById('bill-close-date');
1674
+ var billDueDate = document.getElementById('bill-due-date');
1675
+ var billTotalVal = document.getElementById('bill-total-val');
1676
+ var btnPayBill = document.getElementById('btn-pay-bill');
1677
+ var btnRevertPay = document.getElementById('btn-revert-pay');
1678
+ var billLoading = document.getElementById('bill-loading');
1679
+ var txLoading = document.getElementById('tx-loading');
1680
+
1681
+ // Initial setup
1682
+ var today = new Date();
1683
+ var now = new Date();
1684
+ var params = new URLSearchParams(window.location.search);
1685
+ var defaultMonth = parseInt(params.get('month')) || (now.getMonth() + 1);
1686
+ var defaultYear = parseInt(params.get('year')) || now.getFullYear();
1687
+ monthSelect.value = String(defaultMonth);
1688
+ yearSelect.value = String(defaultYear);
1689
+
1690
+ // Toast system helper
1691
+ function showToast(message, type = 'info') {
1692
+ const toastBox = document.getElementById('toast-box');
1693
+ const toast = document.createElement('div');
1694
+ toast.className = `toast ${type}`;
1695
+
1696
+ let iconClass = 'fa-circle-info';
1697
+ if (type === 'success') iconClass = 'fa-circle-check';
1698
+ if (type === 'error') iconClass = 'fa-circle-exclamation';
1699
+
1700
+ toast.innerHTML = `
1701
+ <i class="fa-solid ${iconClass}"></i>
1702
+ <span>${escapeHtml(message)}</span>
1703
+ <i class="fa-solid fa-xmark toast-close"></i>
1704
+ `;
1705
+
1706
+ toast.querySelector('.toast-close').addEventListener('click', () => {
1707
+ toast.style.animation = 'fadeOut 0.3s forwards';
1708
+ setTimeout(() => toast.remove(), 300);
1709
+ });
1710
+
1711
+ toastBox.appendChild(toast);
1712
+ setTimeout(() => {
1713
+ if (toast.parentNode) {
1714
+ toast.style.animation = 'fadeOut 0.3s forwards';
1715
+ setTimeout(() => toast.remove(), 300);
1716
+ }
1717
+ }, 4000);
1718
+ }
1719
+
1720
+ // Modals management
1721
+ function openModal(id) {
1722
+ document.getElementById(id).classList.add('open');
1723
+ }
1724
+
1725
+ function closeModal(id) {
1726
+ document.getElementById(id).classList.remove('open');
1727
+ }
1728
+
1729
+ // Close modal on ESC key
1730
+ document.addEventListener('keydown', (e) => {
1731
+ if (e.key === 'Escape') {
1732
+ const activeModal = document.querySelector('.modal-overlay.open');
1733
+ if (activeModal) {
1734
+ closeModal(activeModal.id);
1735
+ }
1736
+ }
1737
+ });
1738
+
1739
+ // Setup Month/Year tabs dates
1740
+ function getBillCycleInfo(billType, refMonth, refYear) {
1741
+ let m = parseInt(refMonth);
1742
+ let y = parseInt(refYear);
1743
+
1744
+ if (billType === 'past') {
1745
+ m = m - 1;
1746
+ if (m === 0) { m = 12; y = y - 1; }
1747
+ } else if (billType === 'future') {
1748
+ m = m + 1;
1749
+ if (m === 13) { m = 1; y = y + 1; }
1750
+ }
1751
+
1752
+ return { month: m, year: y };
1753
+ }
1754
+
1755
+ function updateTabLabels() {
1756
+ const m = parseInt(monthSelect.value);
1757
+ const y = parseInt(yearSelect.value);
1758
+
1759
+ const pastCycle = getBillCycleInfo('past', m, y);
1760
+ const futureCycle = getBillCycleInfo('future', m, y);
1761
+
1762
+ const monthNames = ["Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez"];
1763
+
1764
+ document.getElementById('tab-past').textContent = `Passada (${monthNames[pastCycle.month - 1]})`;
1765
+ document.getElementById('tab-current').textContent = `Atual (${monthNames[m - 1]})`;
1766
+ document.getElementById('tab-future').textContent = `Futura (${monthNames[futureCycle.month - 1]})`;
1767
+ }
1768
+
1769
+ function selectBillType(type) {
1770
+ document.querySelectorAll('.bill-tab').forEach(tab => tab.classList.remove('active'));
1771
+ if (type === 'past') document.getElementById('tab-past').classList.add('active');
1772
+ if (type === 'current') document.getElementById('tab-current').classList.add('active');
1773
+ if (type === 'future') document.getElementById('tab-future').classList.add('active');
1774
+
1775
+ selectedBillType = type;
1776
+ loadBillDetails();
1777
+ }
1778
+
1779
+ // Card selection
1780
+ async function selectCard(cardId) {
1781
+ const cardObj = creditCards.find(c => c.id === cardId);
1782
+ if (!cardObj) return;
1783
+
1784
+ activeCard = cardObj;
1785
+
1786
+ // Update edit button visibility
1787
+ const editBtn = document.getElementById('btn-edit-card');
1788
+ if (editBtn) {
1789
+ editBtn.style.display = 'inline-flex';
1790
+ }
1791
+
1792
+ // UI select mockup class update
1793
+ document.querySelectorAll('.credit-card-mockup').forEach(cardEl => {
1794
+ cardEl.classList.remove('active');
1795
+ const isCustom = cardEl.classList.contains('custom-card-style');
1796
+ if (isCustom) {
1797
+ cardEl.style.boxShadow = '';
1798
+ cardEl.style.borderColor = '';
1799
+ }
1800
+ if (cardEl.dataset.id === cardId) {
1801
+ cardEl.classList.add('active');
1802
+ if (isCustom) {
1803
+ const styleInfo = getCardStyle(cardObj.name);
1804
+ cardEl.style.boxShadow = `0 0 25px ${styleInfo.glowColor}`;
1805
+ cardEl.style.borderColor = `hsla(${styleInfo.hue}, 80%, 65%, 0.7)`;
1806
+ }
1807
+ }
1808
+ });
1809
+
1810
+ await determineDefaultBillType();
1811
+ }
1812
+
1813
+ async function determineDefaultBillType() {
1814
+ if (!activeCard) return;
1815
+
1816
+ let defaultBillType = 'current';
1817
+
1818
+ billLoading.classList.add('active');
1819
+ txLoading.classList.add('active');
1820
+
1821
+ const refMonth = parseInt(monthSelect.value);
1822
+ const refYear = parseInt(yearSelect.value);
1823
+ const targetCycle = getBillCycleInfo('current', refMonth, refYear);
1824
+
1825
+ const params = new URLSearchParams({
1826
+ card: activeCard.name,
1827
+ month: targetCycle.month,
1828
+ year: targetCycle.year
1829
+ });
1830
+
1831
+ try {
1832
+ const res = await fetch(`/api/bills?${params.toString()}`);
1833
+ if (res.ok) {
1834
+ const billObj = await res.json();
1835
+ if (billObj && billObj.bill && (billObj.bill.status === 'closed' || billObj.bill.status === 'paid')) {
1836
+ defaultBillType = 'future';
1837
+ }
1838
+ }
1839
+ } catch (err) {
1840
+ console.error("Error checking default bill status", err);
1841
+ }
1842
+
1843
+ document.querySelectorAll('.bill-tab').forEach(tab => tab.classList.remove('active'));
1844
+ if (defaultBillType === 'past') document.getElementById('tab-past').classList.add('active');
1845
+ if (defaultBillType === 'current') document.getElementById('tab-current').classList.add('active');
1846
+ if (defaultBillType === 'future') document.getElementById('tab-future').classList.add('active');
1847
+
1848
+ selectedBillType = defaultBillType;
1849
+ await loadBillDetails();
1850
+ }
1851
+
1852
+ // Fetch cards, accounts and categories
1853
+ async function fetchInitialData() {
1854
+ try {
1855
+ const [cardsRes, accsRes, catsRes] = await Promise.all([
1856
+ fetch('/api/credit-cards'),
1857
+ fetch('/api/accounts'),
1858
+ fetch('/api/categories')
1859
+ ]);
1860
+
1861
+ if (cardsRes.ok) creditCards = await cardsRes.json();
1862
+ if (accsRes.ok) accounts = await accsRes.json();
1863
+ if (catsRes.ok) categories = await catsRes.json();
1864
+
1865
+ // Sort categories
1866
+ categories.sort((a,b) => a.name.localeCompare(b.name));
1867
+
1868
+ // Populate Add Transaction category dropdown
1869
+ const catSelect = document.getElementById('add-category');
1870
+ catSelect.innerHTML = '';
1871
+ categories.forEach(c => {
1872
+ const opt = document.createElement('option');
1873
+ opt.value = c.name;
1874
+ opt.textContent = c.name;
1875
+ catSelect.appendChild(opt);
1876
+ });
1877
+
1878
+ renderCardsCarousel();
1879
+ updateTabLabels();
1880
+
1881
+ // Select first card by default
1882
+ if (creditCards.length > 0) {
1883
+ selectCard(creditCards[0].id);
1884
+ }
1885
+ } catch (err) {
1886
+ console.error("Error loading initial data", err);
1887
+ showToast("Erro ao carregar dados dos cartões e contas.", "error");
1888
+ }
1889
+ }
1890
+
1891
+ // Hash function for stable card characteristics
1892
+ function getCardHash(str) {
1893
+ let hash = 0;
1894
+ for (let i = 0; i < str.length; i++) {
1895
+ hash = str.charCodeAt(i) + ((hash << 5) - hash);
1896
+ }
1897
+ return Math.abs(hash);
1898
+ }
1899
+
1900
+ // Get card styling (preset class or dynamic HSL gradient)
1901
+ function getCardStyle(name) {
1902
+ const lower = name.toLowerCase();
1903
+
1904
+ // Preset keyword check
1905
+ if (lower.includes('infinite')) {
1906
+ return { isPreset: true, className: 'personnalite-infinite', style: '', textClass: '' };
1907
+ }
1908
+ if (lower.includes('ultravioleta') || lower.includes('nubank')) {
1909
+ return { isPreset: true, className: 'ultravioleta-black', style: '', textClass: '' };
1910
+ }
1911
+ if (lower.includes('black') && (lower.includes('itau') || lower.includes('personnalite'))) {
1912
+ return { isPreset: true, className: 'personnalite-black', style: '', textClass: '' };
1913
+ }
1914
+
1915
+ // Dynamic generated gradient for other cards!
1916
+ const hash = getCardHash(name);
1917
+ const hue1 = hash % 360;
1918
+ const hue2 = (hue1 + 35) % 360; // 35 degrees difference for analog harmony
1919
+ const saturation = 45 + (hash % 15); // 45-60%
1920
+ const lightness1 = 12 + (hash % 6); // 12-18%
1921
+ const lightness2 = 25 + (hash % 10); // 25-35%
1922
+
1923
+ const gradient = `linear-gradient(135deg, hsl(${hue1}, ${saturation}%, ${lightness1}%) 0%, hsl(${hue1}, ${saturation}%, ${lightness2}%) 60%, hsl(${hue2}, ${saturation + 10}%, ${lightness2 + 10}%) 100%)`;
1924
+ const border = `1px solid hsla(${hue1}, ${saturation}%, 50%, 0.25)`;
1925
+ const glowColor = `hsla(${hue1}, ${saturation}%, 50%, 0.35)`;
1926
+
1927
+ return {
1928
+ isPreset: false,
1929
+ className: 'custom-card-style',
1930
+ style: `background: ${gradient}; border: ${border};`,
1931
+ glowColor: glowColor,
1932
+ hue: hue1
1933
+ };
1934
+ }
1935
+
1936
+ // Render Card Carousel with Premium mockups
1937
+ function renderCardsCarousel() {
1938
+ cardsContainer.innerHTML = '';
1939
+
1940
+ creditCards.forEach(c => {
1941
+ const styleInfo = getCardStyle(c.name);
1942
+ let mockupType = 'VISA';
1943
+ if (c.name.toLowerCase().includes('mastercard') || c.name.toLowerCase().includes('black') || c.name.toLowerCase().includes('ultravioleta')) {
1944
+ mockupType = 'Mastercard';
1945
+ } else if (c.name.toLowerCase().includes('elo')) {
1946
+ mockupType = 'Elo';
1947
+ } else if (c.name.toLowerCase().includes('amex') || c.name.toLowerCase().includes('express')) {
1948
+ mockupType = 'American Express';
1949
+ }
1950
+
1951
+ // Stable mock digits based on ID/Name
1952
+ const hashVal = getCardHash(c.id || c.name);
1953
+ const lastDigitsVal = String(hashVal % 10000).padStart(4, '0');
1954
+ const lastDigits = `•••• ${lastDigitsVal}`;
1955
+
1956
+ const div = document.createElement('div');
1957
+ div.className = `credit-card-mockup ${styleInfo.className} ${activeCard && activeCard.id === c.id ? 'active' : ''}`;
1958
+ div.dataset.id = c.id;
1959
+ div.onclick = () => selectCard(c.id);
1960
+
1961
+ if (!styleInfo.isPreset) {
1962
+ div.setAttribute('style', styleInfo.style);
1963
+ if (activeCard && activeCard.id === c.id) {
1964
+ div.style.boxShadow = `0 0 25px ${styleInfo.glowColor}`;
1965
+ div.style.borderColor = `hsla(${styleInfo.hue}, 80%, 65%, 0.7)`;
1966
+ }
1967
+ }
1968
+
1969
+ const fmtLimit = window.formatMoney(c.limit, c.currency, { locale: 'pt-BR' });
1970
+
1971
+ div.innerHTML = `
1972
+ <div class="card-header-mock">
1973
+ <div class="card-name-mock">${escapeHtml(c.name)}</div>
1974
+ <div style="font-size:0.75rem; font-weight:700; opacity:0.8; letter-spacing:0.05em;">${mockupType}</div>
1975
+ </div>
1976
+ <div class="card-number-mock">${lastDigits}</div>
1977
+ <div class="card-chip"></div>
1978
+ <div class="card-footer-mock">
1979
+ <div>
1980
+ <div class="card-holder-mock">Titular</div>
1981
+ <div class="card-holder-name">RAFAEL F CARNEIRO</div>
1982
+ </div>
1983
+ <div class="card-limit-mock">
1984
+ <div class="card-limit-label">Limite</div>
1985
+ <div class="card-limit-value">${fmtLimit}</div>
1986
+ </div>
1987
+ </div>
1988
+ `;
1989
+ cardsContainer.appendChild(div);
1990
+ });
1991
+ }
1992
+
1993
+ // Load specific bill details
1994
+ async function loadBillDetails() {
1995
+ if (!activeCard) return;
1996
+
1997
+ billLoading.classList.add('active');
1998
+ txLoading.classList.add('active');
1999
+
2000
+ const refMonth = parseInt(monthSelect.value);
2001
+ const refYear = parseInt(yearSelect.value);
2002
+
2003
+ const targetCycle = getBillCycleInfo(selectedBillType, refMonth, refYear);
2004
+
2005
+ const params = new URLSearchParams({
2006
+ card: activeCard.name,
2007
+ month: targetCycle.month,
2008
+ year: targetCycle.year
2009
+ });
2010
+
2011
+ try {
2012
+ const res = await fetch(`/api/bills?${params.toString()}`);
2013
+
2014
+ if (res.ok) {
2015
+ currentBill = await res.json();
2016
+ } else if (res.status === 404) {
2017
+ // Fallback for not yet created/empty bill
2018
+ const closeDay = activeCard.closingDay || 1;
2019
+ const dueDay = activeCard.dueDay || 8;
2020
+ const padMonth = String(targetCycle.month).padStart(2, '0');
2021
+
2022
+ currentBill = {
2023
+ bill: {
2024
+ id: null,
2025
+ month: targetCycle.month,
2026
+ year: targetCycle.year,
2027
+ closeDate: `${targetCycle.year}-${padMonth}-${String(closeDay).padStart(2, '0')}`,
2028
+ dueDate: `${targetCycle.year}-${padMonth}-${String(dueDay).padStart(2, '0')}`,
2029
+ status: 'open',
2030
+ statusLabel: 'Aberta'
2031
+ },
2032
+ cardName: activeCard.name,
2033
+ transactions: [],
2034
+ total: 0
2035
+ };
2036
+ } else {
2037
+ throw new Error("Erro de conexão com o servidor");
2038
+ }
2039
+
2040
+ renderBillSummary();
2041
+ renderTransactionsTable();
2042
+ } catch (err) {
2043
+ console.error("Error loading bill details", err);
2044
+ showToast("Erro ao carregar os detalhes da fatura.", "error");
2045
+ } finally {
2046
+ billLoading.classList.remove('active');
2047
+ txLoading.classList.remove('active');
2048
+ }
2049
+ }
2050
+
2051
+ // Render left summary panel
2052
+ function renderBillSummary() {
2053
+ if (!currentBill) return;
2054
+
2055
+ const b = currentBill.bill || {};
2056
+ const status = b.status || 'open';
2057
+ const statusLabel = b.statusLabel || 'Aberta';
2058
+
2059
+ // Set badge status text & class
2060
+ billStatusBadge.className = `bill-status-badge ${status}`;
2061
+ billStatusBadge.innerHTML = `
2062
+ <i class="fa-solid ${status === 'paid' ? 'fa-circle-check' : (status === 'closed' ? 'fa-lock' : 'fa-lock-open')}"></i>
2063
+ <span>${statusLabel}</span>
2064
+ `;
2065
+
2066
+ // Dates
2067
+ const fmtDate = (dStr) => {
2068
+ if (!dStr) return '-';
2069
+ const parts = dStr.split('-');
2070
+ return `${parts[2]}/${parts[1]}/${parts[0]}`;
2071
+ };
2072
+ billCloseDate.textContent = fmtDate(b.closeDate);
2073
+ billDueDate.textContent = fmtDate(b.dueDate);
2074
+
2075
+ // Total Amount
2076
+ document.getElementById('bill-total-label').textContent = `Total da Fatura (${activeCard.currency})`;
2077
+
2078
+ const fmtAmount = window.formatMoney(currentBill.total || 0, activeCard.currency);
2079
+
2080
+ billTotalVal.textContent = fmtAmount;
2081
+
2082
+ // Handle actions visibility
2083
+ if (status === 'paid') {
2084
+ btnPayBill.style.display = 'none';
2085
+ btnRevertPay.style.display = 'flex';
2086
+ } else {
2087
+ btnPayBill.style.display = 'flex';
2088
+ btnRevertPay.style.display = 'none';
2089
+ btnPayBill.disabled = (currentBill.total === 0);
2090
+ }
2091
+ }
2092
+
2093
+ // Toggle Table sorting
2094
+ function toggleSort(column) {
2095
+ if (sortColumn === column) {
2096
+ sortDirection = sortDirection === 'asc' ? 'desc' : 'asc';
2097
+ } else {
2098
+ sortColumn = column;
2099
+ sortDirection = 'asc';
2100
+ }
2101
+ updateSortHeaders();
2102
+ renderTransactionsTable();
2103
+ }
2104
+ function handleTxSearch(value) {
2105
+ searchTerm = value.trim().toLowerCase();
2106
+ renderTransactionsTable();
2107
+ }
2108
+ function updateSortHeaders() {
2109
+ const columns = ['date', 'description', 'category', 'amount'];
2110
+ columns.forEach(col => {
2111
+ const link = document.getElementById(`sort-link-${col}`);
2112
+ if (!link) return;
2113
+
2114
+ if (sortColumn === col) {
2115
+ link.className = 'sort-link active';
2116
+ const label = col === 'date' ? 'Data' : col === 'description' ? 'Descrição' : col === 'category' ? 'Categoria' : 'Valor';
2117
+ link.innerHTML = `${label} ${sortDirection === 'asc' ? '▲' : '▼'}`;
2118
+ } else {
2119
+ link.className = 'sort-link';
2120
+ const label = col === 'date' ? 'Data' : col === 'description' ? 'Descrição' : col === 'category' ? 'Categoria' : 'Valor';
2121
+ link.innerHTML = label;
2122
+ }
2123
+ });
2124
+ }
2125
+
2126
+ // Render transactions list
2127
+ // Render a single transaction item in the list
2128
+ // Toggle expand/collapse drawer for transaction notes
2129
+ function toggleTxExpand(event, el) {
2130
+ if (event.target.closest('button') || event.target.closest('.action-btn') || event.target.closest('a')) {
2131
+ return;
2132
+ }
2133
+ el.classList.toggle('expanded');
2134
+ }
2135
+
2136
+ // Render a single transaction item in the list
2137
+ function renderTxItem(t, container, showDateInline) {
2138
+ const amtFormatted = window.formatMoney(t.amount, t.currency);
2139
+
2140
+ const isIncome = t.type === 'transfer' || t.type === 'income';
2141
+ const amountClass = isIncome ? 'income' : 'expense';
2142
+ const amountPrefix = isIncome ? '+' : '-';
2143
+
2144
+ // Get Category Colors & Icons
2145
+ const categoryMap = {
2146
+ 'Bares e Restaurantes': { icon: 'fa-utensils', color: '#8b5cf6', bg: 'rgba(139, 92, 246, 0.1)', text: '#c084fc' },
2147
+ 'Transporte': { icon: 'fa-car', color: '#3b82f6', bg: 'rgba(59, 130, 246, 0.1)', text: '#93c5fd' },
2148
+ 'Compras': { icon: 'fa-bag-shopping', color: '#ec4899', bg: 'rgba(236, 72, 153, 0.1)', text: '#f9a8d4' },
2149
+ 'Supermercado': { icon: 'fa-cart-shopping', color: '#f59e0b', bg: 'rgba(245, 158, 11, 0.1)', text: '#fcd34d' },
2150
+ 'Educação': { icon: 'fa-graduation-cap', color: '#f97316', bg: 'rgba(249, 115, 22, 0.1)', text: '#fdba74' },
2151
+ 'Moradia': { icon: 'fa-house', color: '#f43f5e', bg: 'rgba(244, 63, 94, 0.1)', text: '#fda4af' },
2152
+ 'Lazer': { icon: 'fa-gamepad', color: '#84cc16', bg: 'rgba(132, 204, 22, 0.1)', text: '#bef264' },
2153
+ 'Assinaturas': { icon: 'fa-rotate', color: '#06b6d4', bg: 'rgba(6, 182, 212, 0.1)', text: '#67e8f9' },
2154
+ 'TV / Internet / Telefone': { icon: 'fa-wifi', color: '#10b981', bg: 'rgba(16, 185, 129, 0.1)', text: '#6ee7b7' },
2155
+ 'Cuidados Pessoais': { icon: 'fa-heart', color: '#ec4899', bg: 'rgba(236, 72, 153, 0.1)', text: '#f9a8d4' },
2156
+ 'Saúde': { icon: 'fa-stethoscope', color: '#ef4444', bg: 'rgba(239, 68, 68, 0.1)', text: '#fca5a5' },
2157
+ 'Empréstimos p/ Terc': { icon: 'fa-hand-holding-dollar', color: '#64748b', bg: 'rgba(100, 116, 139, 0.1)', text: '#cbd5e1' }
2158
+ };
2159
+
2160
+ let catName = t.categoryName || 'Sem Categoria';
2161
+ let colColors = categoryMap[catName] || { icon: 'fa-receipt', color: '#a855f7', bg: 'rgba(168, 85, 247, 0.1)', text: '#d8b4fe' };
2162
+
2163
+ // Special overrides for payments
2164
+ if (isIncome) {
2165
+ catName = 'Pagamento';
2166
+ colColors = { icon: 'fa-credit-card', color: '#10b981', bg: 'rgba(16, 185, 129, 0.1)', text: '#6ee7b7' };
2167
+ }
2168
+
2169
+ const isPaid = currentBill.bill && currentBill.bill.status === 'paid';
2170
+ const actionButtons = isPaid
2171
+ ? `<span style="font-size:0.75rem; color:var(--text-dark); font-style:italic; min-width: 80px; text-align: center;">Fatura Paga</span>`
2172
+ : `
2173
+ <div class="tx-item-actions">
2174
+ ${t.status === 'pending' ? `
2175
+ <button class="action-btn btn-confirm-icon" title="Confirmar" onclick="confirmTx('${t.id}', '${escapeJsAttr(t.description)}', '${t.date}', ${t.amount})">
2176
+ <i class="fa-solid fa-check"></i>
2177
+ </button>
2178
+ ` : ''}
2179
+ <button class="action-btn btn-change-icon" title="Mover Fatura" onclick="openReassignModal('${t.id}', '${escapeJsAttr(t.description)}', '${t.date}', ${t.amount})">
2180
+ <i class="fa-solid fa-calendar-days"></i>
2181
+ </button>
2182
+ <button class="action-btn btn-delete-icon" title="Excluir" onclick="deleteTx('${t.id}', '${escapeJsAttr(t.description)}')">
2183
+ <i class="fa-solid fa-trash-can"></i>
2184
+ </button>
2185
+ </div>
2186
+ `;
2187
+
2188
+ const txItem = document.createElement('div');
2189
+ if (t.note) {
2190
+ txItem.className = 'tx-list-item has-note';
2191
+ txItem.setAttribute('onclick', 'toggleTxExpand(event, this)');
2192
+ } else {
2193
+ txItem.className = 'tx-list-item';
2194
+ }
2195
+
2196
+ // Compile tags HTML
2197
+ const tagsHtml = t.tags && t.tags.length > 0
2198
+ ? `<div style="display:flex; gap: 4px; flex-wrap:wrap; margin-top: 2px;">
2199
+ ${t.tags.map(tag => `<span class="badge-cat" style="font-size:0.65rem; padding:0.5px 3px; border-radius:3px; 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.55rem;"></i> ${escapeHtml(tag)}</span>`).join('')}
2200
+ </div>`
2201
+ : '';
2202
+
2203
+ // Formatting inline date if shown flat
2204
+ let inlineDateHtml = '';
2205
+ if (showDateInline) {
2206
+ const dateObj = new Date(t.date + 'T12:00:00');
2207
+ const day = String(dateObj.getDate()).padStart(2, '0');
2208
+ const month = String(dateObj.getMonth() + 1).padStart(2, '0');
2209
+ inlineDateHtml = `<span style="font-size: 0.75rem; color: var(--text-muted); font-weight: 500;">• ${day}/${month}</span>`;
2210
+ }
2211
+
2212
+ txItem.innerHTML = `
2213
+ <div class="tx-item-row-content">
2214
+ <div class="tx-item-left">
2215
+ <div class="tx-item-icon" style="background: ${colColors.bg}; border-color: rgba(255, 255, 255, 0.05); color: ${colColors.color};">
2216
+ <i class="fa-solid ${colColors.icon}"></i>
2217
+ </div>
2218
+ <div class="tx-item-details">
2219
+ <span class="tx-item-desc">${escapeHtml(t.description)}</span>
2220
+ <div class="tx-item-meta">
2221
+ ${tagsHtml}
2222
+ </div>
2223
+ </div>
2224
+ </div>
2225
+ <!-- Category badge in the middle to prevent tag/category confusion -->
2226
+ <div class="tx-item-category-middle" style="width: 155px; flex-shrink: 0; text-align: left; display: flex; align-items: center; gap: 6px;">
2227
+ <span class="badge-cat" style="background: ${colColors.bg}; border-color: ${colColors.bg}; color: ${colColors.text}; font-size: 0.7rem; font-weight: 500; padding: 1px 6px;">
2228
+ ${escapeHtml(catName)}
2229
+ </span>
2230
+ ${inlineDateHtml}
2231
+ </div>
2232
+ <div class="tx-item-right">
2233
+ <span class="tx-item-amount ${amountClass}">${amountPrefix} ${amtFormatted}</span>
2234
+ ${actionButtons}
2235
+ ${t.note ? `<i class="fa-solid fa-chevron-down tx-expand-chevron" style="font-size: 0.75rem; color: var(--text-muted); transition: transform 0.2s ease; margin-left: 0.25rem;"></i>` : ''}
2236
+ </div>
2237
+ </div>
2238
+ ${t.note ? `
2239
+ <div class="tx-item-drawer">
2240
+ <div class="tx-item-drawer-inner">
2241
+ <i class="fa-solid fa-comment-dots" style="color: var(--accent-primary); margin-right: 8px; margin-top: 2px;"></i>
2242
+ <span>${escapeHtml(t.note)}</span>
2243
+ </div>
2244
+ </div>
2245
+ ` : ''}
2246
+ `;
2247
+ container.appendChild(txItem);
2248
+ }
2249
+
2250
+ function renderTransactionsTable() {
2251
+ updateSortHeaders();
2252
+ txListContainer.innerHTML = '';
2253
+
2254
+ const txs = currentBill ? currentBill.transactions || [] : [];
2255
+
2256
+ // Apply search filter
2257
+ let filteredTxs = [...txs];
2258
+ if (searchTerm) {
2259
+ filteredTxs = filteredTxs.filter(t => {
2260
+ const descMatch = t.description.toLowerCase().includes(searchTerm);
2261
+ // Special override for payment category name
2262
+ const isIncome = t.type === 'transfer' || t.type === 'income';
2263
+ const catName = isIncome ? 'pagamento' : (t.categoryName || 'Sem Categoria').toLowerCase();
2264
+ const catMatch = catName.includes(searchTerm);
2265
+ const noteMatch = t.note ? t.note.toLowerCase().includes(searchTerm) : false;
2266
+ const tagsMatch = t.tags ? t.tags.some(tag => tag.toLowerCase().includes(searchTerm)) : false;
2267
+ return descMatch || catMatch || noteMatch || tagsMatch;
2268
+ });
2269
+ }
2270
+
2271
+ if (filteredTxs.length === 0) {
2272
+ noTxMsg.style.display = 'block';
2273
+ noTxMsg.innerHTML = searchTerm
2274
+ ? `<i class="fa-solid fa-magnifying-glass"></i> Nenhum resultado encontrado para "${escapeHtml(searchTerm)}".`
2275
+ : `<i class="fa-regular fa-folder-open"></i> Nenhum lançamento encontrado para esta fatura.`;
2276
+ document.getElementById('bill-txs-list').style.display = 'none';
2277
+ return;
2278
+ }
2279
+
2280
+ noTxMsg.style.display = 'none';
2281
+ document.getElementById('bill-txs-list').style.display = 'flex';
2282
+
2283
+ // Sorting logic
2284
+ const sortedTxs = [...filteredTxs];
2285
+ sortedTxs.sort((a, b) => {
2286
+ let valA, valB;
2287
+
2288
+ if (sortColumn === 'date') {
2289
+ valA = a.date;
2290
+ valB = b.date;
2291
+ } else if (sortColumn === 'description') {
2292
+ valA = a.description.toLowerCase();
2293
+ valB = b.description.toLowerCase();
2294
+ } else if (sortColumn === 'category') {
2295
+ valA = (a.categoryName || 'Sem Categoria').toLowerCase();
2296
+ valB = (b.categoryName || 'Sem Categoria').toLowerCase();
2297
+ } else if (sortColumn === 'amount') {
2298
+ valA = a.amount;
2299
+ valB = b.amount;
2300
+ }
2301
+
2302
+ if (valA < valB) return sortDirection === 'asc' ? -1 : 1;
2303
+ if (valA > valB) return sortDirection === 'asc' ? 1 : -1;
2304
+
2305
+ if (sortColumn !== 'date') {
2306
+ return a.date.localeCompare(b.date);
2307
+ }
2308
+ return 0;
2309
+ });
2310
+
2311
+ if (sortColumn === 'date') {
2312
+ // Grouping by Date
2313
+ const groups = {};
2314
+ sortedTxs.forEach(t => {
2315
+ const dateKey = t.date;
2316
+ if (!groups[dateKey]) {
2317
+ groups[dateKey] = {
2318
+ dateStr: dateKey,
2319
+ txs: [],
2320
+ total: 0
2321
+ };
2322
+ }
2323
+ groups[dateKey].txs.push(t);
2324
+ // Deduct payments from the totalizer, add purchases
2325
+ const isIncome = t.type === 'transfer' || t.type === 'income';
2326
+ if (isIncome) {
2327
+ groups[dateKey].total -= t.amount;
2328
+ } else {
2329
+ groups[dateKey].total += t.amount;
2330
+ }
2331
+ });
2332
+
2333
+ // Sort day groups by date (respecting sortDirection)
2334
+ const sortedGroupKeys = Object.keys(groups).sort((a, b) => {
2335
+ return sortDirection === 'asc' ? a.localeCompare(b) : b.localeCompare(a);
2336
+ });
2337
+
2338
+ sortedGroupKeys.forEach(dateKey => {
2339
+ const group = groups[dateKey];
2340
+
2341
+ // Formats for group header
2342
+ const dateObj = new Date(dateKey + 'T12:00:00');
2343
+ const formattedDate = dateObj.toLocaleDateString('pt-BR', { weekday: 'long', day: 'numeric', month: 'long' });
2344
+ const capitalizedDate = formattedDate.charAt(0).toUpperCase() + formattedDate.slice(1);
2345
+
2346
+ const count = group.txs.length;
2347
+ const groupTotalStr = window.formatMoney(group.total, activeCard?.currency ?? window.DEFAULT_CURRENCY);
2348
+
2349
+ // Create day group element
2350
+ const dayGroupDiv = document.createElement('div');
2351
+ dayGroupDiv.className = 'day-group';
2352
+
2353
+ dayGroupDiv.innerHTML = `
2354
+ <div class="day-group-header">
2355
+ <span class="day-group-date"><i class="fa-solid fa-calendar-day"></i> ${capitalizedDate}</span>
2356
+ <span class="day-group-summary">${count} ${count === 1 ? 'lançamento' : 'lançamentos'} • <span class="day-group-sum-val">${groupTotalStr}</span></span>
2357
+ </div>
2358
+ <div class="day-group-items" id="items-${dateKey}"></div>
2359
+ `;
2360
+ txListContainer.appendChild(dayGroupDiv);
2361
+
2362
+ const itemsContainer = document.getElementById(`items-${dateKey}`);
2363
+
2364
+ // Render transactions for this day group
2365
+ group.txs.forEach(t => {
2366
+ renderTxItem(t, itemsContainer, false);
2367
+ });
2368
+ });
2369
+ } else {
2370
+ // Flat list rendering for global sorting (without day groups)
2371
+ const flatGroupDiv = document.createElement('div');
2372
+ flatGroupDiv.className = 'day-group-items';
2373
+ txListContainer.appendChild(flatGroupDiv);
2374
+
2375
+ sortedTxs.forEach(t => {
2376
+ renderTxItem(t, flatGroupDiv, true);
2377
+ });
2378
+ }
2379
+ }
2380
+
2381
+ // Open modal to Add transaction
2382
+ function openAddTxModal() {
2383
+ if (!activeCard) return;
2384
+
2385
+ // Reset form
2386
+ document.getElementById('form-add-tx').reset();
2387
+
2388
+ // Set default date
2389
+ const refMonth = parseInt(monthSelect.value);
2390
+ const refYear = parseInt(yearSelect.value);
2391
+ const padMonth = String(refMonth).padStart(2, '0');
2392
+ document.getElementById('add-date').value = `${refYear}-${padMonth}-01`;
2393
+
2394
+ // Populate Bill cycle options (Past, Current, Future relative)
2395
+ const cycleSelect = document.getElementById('add-bill-cycle');
2396
+ cycleSelect.innerHTML = '<option value="auto">Automática (Baseada na data)</option>';
2397
+
2398
+ const monthNames = ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"];
2399
+
2400
+ const optionsCycles = [
2401
+ getBillCycleInfo('past', refMonth, refYear),
2402
+ { month: refMonth, year: refYear },
2403
+ getBillCycleInfo('future', refMonth, refYear)
2404
+ ];
2405
+
2406
+ optionsCycles.forEach(cy => {
2407
+ const opt = document.createElement('option');
2408
+ opt.value = `${cy.month}_${cy.year}`;
2409
+ opt.textContent = `${monthNames[cy.month - 1]} ${cy.year}`;
2410
+ if (cy.month === refMonth && cy.year === refYear) {
2411
+ opt.selected = true; // Default target
2412
+ }
2413
+ cycleSelect.appendChild(opt);
2414
+ });
2415
+
2416
+ applyCurrencyPrecision(['add-amount'], activeCard?.currency ?? window.DEFAULT_CURRENCY);
2417
+ openModal('modal-add-tx');
2418
+ }
2419
+
2420
+ // Add Transaction submit
2421
+ async function handleAddTxSubmit(e) {
2422
+ e.preventDefault();
2423
+ if (!activeCard) return;
2424
+
2425
+ const desc = document.getElementById('add-desc').value;
2426
+ const amt = parseFloat(document.getElementById('add-amount').value);
2427
+ const dt = document.getElementById('add-date').value;
2428
+ const cat = document.getElementById('add-category').value;
2429
+ const billCycle = document.getElementById('add-bill-cycle').value;
2430
+ const note = document.getElementById('add-note').value;
2431
+ const tagsStr = document.getElementById('add-tags').value;
2432
+ const tags = tagsStr.split(',')
2433
+ .map(t => t.trim())
2434
+ .filter(t => t.length > 0);
2435
+
2436
+ const payload = {
2437
+ description: desc,
2438
+ amount: amt,
2439
+ type: 'expense',
2440
+ date: dt,
2441
+ card: activeCard.name,
2442
+ category: cat,
2443
+ note: note,
2444
+ idempotencyKey: `purchase-${dt}-${desc}-${amt}-${Math.random().toString(36).substr(2, 9)}`
2445
+ };
2446
+
2447
+ if (tags.length > 0) {
2448
+ payload.tags = tags;
2449
+ }
2450
+
2451
+ // Explicit bill re-assignment if not auto
2452
+ if (billCycle !== 'auto') {
2453
+ const parts = billCycle.split('_');
2454
+ payload.billMonth = parseInt(parts[0]);
2455
+ payload.billYear = parseInt(parts[1]);
2456
+ }
2457
+
2458
+ closeModal('modal-add-tx');
2459
+ txLoading.classList.add('active');
2460
+ billLoading.classList.add('active');
2461
+
2462
+ try {
2463
+ const res = await fetch('/api/credit-cards/purchases', {
2464
+ method: 'POST',
2465
+ headers: { 'Content-Type': 'application/json' },
2466
+ body: JSON.stringify(payload)
2467
+ });
2468
+
2469
+ if (!res.ok) {
2470
+ const errRes = await res.json();
2471
+ throw new Error(errRes.error?.hint || errRes.error?.message || "Falha ao criar transação");
2472
+ }
2473
+
2474
+ showToast(`Compra "${desc}" adicionada com sucesso!`, 'success');
2475
+ await loadBillDetails();
2476
+ } catch (err) {
2477
+ console.error("Add transaction error", err);
2478
+ showToast(`Erro ao adicionar: ${err.message}`, 'error');
2479
+ } finally {
2480
+ txLoading.classList.remove('active');
2481
+ billLoading.classList.remove('active');
2482
+ }
2483
+ }
2484
+
2485
+ // Amount inputs accept the currency's own precision (a BTC limit of 0.05, a USDC one of
2486
+ // 1.000001), not a fiat cent.
2487
+ function applyCurrencyPrecision(inputIds, code) {
2488
+ const decimals = ((window.__appCurrencies || {})[code] || {}).decimals ?? 2;
2489
+ const step = (10 ** -decimals).toFixed(decimals);
2490
+ inputIds.forEach(id => {
2491
+ const input = document.getElementById(id);
2492
+ input.step = step;
2493
+ input.min = step;
2494
+ });
2495
+ }
2496
+
2497
+ // Fills a currency <select> from the shell's currency metadata (sorted by code, with its
2498
+ // symbol) and preselects `selected`; a code the metadata lacks is still offered so a card
2499
+ // never shows a currency other than its own.
2500
+ function fillCurrencyOptions(selectId, selected) {
2501
+ const meta = window.__appCurrencies || {};
2502
+ const codes = Array.from(new Set([...Object.keys(meta), selected])).sort();
2503
+ const select = document.getElementById(selectId);
2504
+ select.innerHTML = codes.map(code => {
2505
+ const label = meta[code] ? `${code} (${meta[code].symbol})` : code;
2506
+ return `<option value="${escapeHtml(code)}">${escapeHtml(label)}</option>`;
2507
+ }).join('');
2508
+ select.value = selected;
2509
+ applyCurrencyPrecision(
2510
+ selectId === 'card-add-currency' ? ['card-add-limit'] : ['card-edit-limit'],
2511
+ selected,
2512
+ );
2513
+ }
2514
+
2515
+ // Open modal to Add credit card
2516
+ function openAddCardModal() {
2517
+ // Reset form
2518
+ document.getElementById('form-add-card').reset();
2519
+
2520
+ // Populate payment account select
2521
+ const payAccSelect = document.getElementById('card-add-payment-account');
2522
+ payAccSelect.innerHTML = '<option value="">Selecionar...</option>';
2523
+ payAccSelect.style.color = 'var(--text-muted)';
2524
+ const filteredAccounts = accounts.filter(acc => acc.type === 'checking' || acc.type === 'savings');
2525
+ filteredAccounts.forEach(acc => {
2526
+ const opt = document.createElement('option');
2527
+ opt.value = acc.name;
2528
+ opt.textContent = acc.name;
2529
+ opt.style.color = 'var(--text-main)'; // Reset color inside options
2530
+ payAccSelect.appendChild(opt);
2531
+ });
2532
+
2533
+ // Change color dynamically when selected
2534
+ payAccSelect.onchange = () => {
2535
+ if (payAccSelect.value === '') {
2536
+ payAccSelect.style.color = 'var(--text-muted)';
2537
+ } else {
2538
+ payAccSelect.style.color = 'var(--text-main)';
2539
+ }
2540
+ };
2541
+
2542
+ // Default select values
2543
+ fillCurrencyOptions('card-add-currency', window.DEFAULT_CURRENCY);
2544
+ document.getElementById('card-add-closing-day').value = 5;
2545
+ document.getElementById('card-add-due-day').value = 15;
2546
+
2547
+ // Trigger preview render
2548
+ updateCardPreview();
2549
+
2550
+ openModal('modal-add-card');
2551
+ }
2552
+
2553
+ // Update Card design Live Preview
2554
+ function updateCardPreview() {
2555
+ const nameInput = document.getElementById('card-add-name');
2556
+ const limitInput = document.getElementById('card-add-limit');
2557
+
2558
+ const name = nameInput.value || 'Nome do Cartão';
2559
+ const limitVal = parseFloat(limitInput.value) || 0;
2560
+ const currency = document.getElementById('card-add-currency').value || window.DEFAULT_CURRENCY;
2561
+ applyCurrencyPrecision(['card-add-limit'], currency);
2562
+
2563
+ // Determine card brand logo
2564
+ let brand = 'VISA';
2565
+ const lowerName = name.toLowerCase();
2566
+ if (lowerName.includes('mastercard') || lowerName.includes('black') || lowerName.includes('ultravioleta')) {
2567
+ brand = 'Mastercard';
2568
+ } else if (lowerName.includes('elo')) {
2569
+ brand = 'Elo';
2570
+ } else if (lowerName.includes('amex') || lowerName.includes('express')) {
2571
+ brand = 'American Express';
2572
+ }
2573
+
2574
+ // Stable card number mock digits from name hash
2575
+ const hash = getCardHash(name);
2576
+ const lastDigitsVal = String(hash % 10000).padStart(4, '0');
2577
+
2578
+ // Get style info
2579
+ const styleInfo = getCardStyle(name);
2580
+ const previewEl = document.getElementById('card-preview-element');
2581
+ if (!previewEl) return;
2582
+
2583
+ // Reset classes and styles
2584
+ previewEl.className = `credit-card-mockup ${styleInfo.className} active`; // Always active/glowing in preview!
2585
+ previewEl.style.cssText = 'pointer-events: none; width: 320px; height: 190px; margin: 0;';
2586
+
2587
+ if (!styleInfo.isPreset) {
2588
+ previewEl.setAttribute('style', `pointer-events: none; width: 320px; height: 190px; margin: 0; ${styleInfo.style}`);
2589
+ previewEl.style.boxShadow = `0 0 25px ${styleInfo.glowColor}`;
2590
+ previewEl.style.borderColor = `hsla(${styleInfo.hue}, 80%, 65%, 0.7)`;
2591
+ } else {
2592
+ // Preset styling glows
2593
+ if (styleInfo.className === 'personnalite-black') {
2594
+ previewEl.style.borderColor = '#d4af37';
2595
+ previewEl.style.boxShadow = '0 0 25px rgba(212, 175, 55, 0.35)';
2596
+ } else if (styleInfo.className === 'personnalite-infinite') {
2597
+ previewEl.style.borderColor = '#00c8ff';
2598
+ previewEl.style.boxShadow = '0 0 25px rgba(0, 200, 255, 0.35)';
2599
+ } else if (styleInfo.className === 'ultravioleta-black') {
2600
+ previewEl.style.borderColor = '#a855f7';
2601
+ previewEl.style.boxShadow = '0 0 25px rgba(168, 85, 247, 0.35)';
2602
+ }
2603
+ }
2604
+
2605
+ const fmtLimit = window.formatMoney(limitVal, currency, { locale: 'pt-BR' });
2606
+
2607
+ previewEl.innerHTML = `
2608
+ <div class="card-header-mock">
2609
+ <div class="card-name-mock">${escapeHtml(name)}</div>
2610
+ <div style="font-size:0.75rem; font-weight:700; opacity:0.8; letter-spacing:0.05em;">${brand}</div>
2611
+ </div>
2612
+ <div class="card-number-mock">•••• ${lastDigitsVal}</div>
2613
+ <div class="card-chip"></div>
2614
+ <div class="card-footer-mock">
2615
+ <div>
2616
+ <div class="card-holder-mock">Titular</div>
2617
+ <div class="card-holder-name">RAFAEL F CARNEIRO</div>
2618
+ </div>
2619
+ <div class="card-limit-mock">
2620
+ <div class="card-limit-label">Limite</div>
2621
+ <div class="card-limit-value">${fmtLimit}</div>
2622
+ </div>
2623
+ </div>
2624
+ `;
2625
+ }
2626
+
2627
+ // Add Credit Card submit
2628
+ async function handleAddCardSubmit(e) {
2629
+ e.preventDefault();
2630
+
2631
+ const name = document.getElementById('card-add-name').value;
2632
+ const limit = parseFloat(document.getElementById('card-add-limit').value);
2633
+ const closing = parseInt(document.getElementById('card-add-closing-day').value);
2634
+ const due = parseInt(document.getElementById('card-add-due-day').value);
2635
+ const currency = document.getElementById('card-add-currency').value;
2636
+ const payAcc = document.getElementById('card-add-payment-account').value;
2637
+
2638
+ const payload = {
2639
+ name: name,
2640
+ limit: limit,
2641
+ closingDay: closing,
2642
+ dueDay: due,
2643
+ currency: currency
2644
+ };
2645
+
2646
+ if (payAcc) {
2647
+ payload.paymentAccount = payAcc;
2648
+ }
2649
+
2650
+ closeModal('modal-add-card');
2651
+ billLoading.classList.add('active');
2652
+
2653
+ try {
2654
+ const res = await fetch('/api/credit-cards', {
2655
+ method: 'POST',
2656
+ headers: { 'Content-Type': 'application/json' },
2657
+ body: JSON.stringify(payload)
2658
+ });
2659
+
2660
+ if (!res.ok) {
2661
+ const errRes = await res.json();
2662
+ throw new Error(errRes.error?.message || "Falha ao criar cartão de crédito");
2663
+ }
2664
+
2665
+ showToast(`Cartão "${name}" criado com sucesso!`, 'success');
2666
+
2667
+ // Reload cards and select the new one!
2668
+ const freshCardsRes = await fetch('/api/credit-cards');
2669
+ if (freshCardsRes.ok) {
2670
+ creditCards = await freshCardsRes.json();
2671
+ renderCardsCarousel();
2672
+ // Find the newly created card and select it
2673
+ const newCardObj = creditCards.find(c => c.name === name);
2674
+ if (newCardObj) {
2675
+ selectCard(newCardObj.id);
2676
+ }
2677
+ }
2678
+ } catch (err) {
2679
+ console.error("Create credit card error", err);
2680
+ showToast(`Erro ao criar cartão: ${err.message}`, 'error');
2681
+ } finally {
2682
+ billLoading.classList.remove('active');
2683
+ }
2684
+ }
2685
+
2686
+ // Open modal to Edit credit card
2687
+ function openEditCardModal() {
2688
+ if (!activeCard) return;
2689
+
2690
+ // Populate form fields with selected card details
2691
+ document.getElementById('card-edit-name').value = activeCard.name;
2692
+ document.getElementById('card-edit-limit').value = activeCard.limit;
2693
+ document.getElementById('card-edit-closing-day').value = activeCard.closingDay;
2694
+ document.getElementById('card-edit-due-day').value = activeCard.dueDay;
2695
+ fillCurrencyOptions('card-edit-currency', activeCard.currency);
2696
+
2697
+ // Populate payment account select
2698
+ const payAccSelect = document.getElementById('card-edit-payment-account');
2699
+ payAccSelect.innerHTML = '<option value="">Selecionar...</option>';
2700
+ payAccSelect.style.color = 'var(--text-muted)';
2701
+
2702
+ // Filter accounts of same currency
2703
+ const filteredAccounts = accounts.filter(acc => (acc.type === 'checking' || acc.type === 'savings') && acc.currency === activeCard.currency);
2704
+ filteredAccounts.forEach(acc => {
2705
+ const opt = document.createElement('option');
2706
+ opt.value = acc.name;
2707
+ opt.textContent = acc.name;
2708
+ opt.style.color = 'var(--text-main)'; // Reset color inside options
2709
+ if (activeCard.paymentAccountId === acc.id || activeCard.paymentAccountName === acc.name) {
2710
+ opt.selected = true;
2711
+ payAccSelect.style.color = 'var(--text-main)';
2712
+ }
2713
+ payAccSelect.appendChild(opt);
2714
+ });
2715
+
2716
+ // Change color dynamically when selected
2717
+ payAccSelect.onchange = () => {
2718
+ if (payAccSelect.value === '') {
2719
+ payAccSelect.style.color = 'var(--text-muted)';
2720
+ } else {
2721
+ payAccSelect.style.color = 'var(--text-main)';
2722
+ }
2723
+ };
2724
+
2725
+ // Trigger preview render
2726
+ updateCardEditPreview();
2727
+
2728
+ openModal('modal-edit-card');
2729
+ }
2730
+
2731
+ // Update Card design Live Preview (Edit Modal)
2732
+ function updateCardEditPreview() {
2733
+ const nameInput = document.getElementById('card-edit-name');
2734
+ const limitInput = document.getElementById('card-edit-limit');
2735
+
2736
+ const name = nameInput.value || 'Nome do Cartão';
2737
+ const limitVal = parseFloat(limitInput.value) || 0;
2738
+ const currency = document.getElementById('card-edit-currency').value || window.DEFAULT_CURRENCY;
2739
+
2740
+ // Determine card brand logo
2741
+ let brand = 'VISA';
2742
+ const lowerName = name.toLowerCase();
2743
+ if (lowerName.includes('mastercard') || lowerName.includes('black') || lowerName.includes('ultravioleta')) {
2744
+ brand = 'Mastercard';
2745
+ } else if (lowerName.includes('elo')) {
2746
+ brand = 'Elo';
2747
+ } else if (lowerName.includes('amex') || lowerName.includes('express')) {
2748
+ brand = 'American Express';
2749
+ }
2750
+
2751
+ // Stable card number mock digits from name hash
2752
+ const hash = getCardHash(name);
2753
+ const lastDigitsVal = String(hash % 10000).padStart(4, '0');
2754
+
2755
+ // Get style info
2756
+ const styleInfo = getCardStyle(name);
2757
+ const previewEl = document.getElementById('card-edit-preview-element');
2758
+ if (!previewEl) return;
2759
+
2760
+ // Reset classes and styles
2761
+ previewEl.className = `credit-card-mockup ${styleInfo.className} active`; // Always active/glowing in preview!
2762
+ previewEl.style.cssText = 'pointer-events: none; width: 320px; height: 190px; margin: 0;';
2763
+
2764
+ if (!styleInfo.isPreset) {
2765
+ previewEl.setAttribute('style', `pointer-events: none; width: 320px; height: 190px; margin: 0; ${styleInfo.style}`);
2766
+ previewEl.style.boxShadow = `0 0 25px ${styleInfo.glowColor}`;
2767
+ previewEl.style.borderColor = `hsla(${styleInfo.hue}, 80%, 65%, 0.7)`;
2768
+ } else {
2769
+ // Preset styling glows
2770
+ if (styleInfo.className === 'personnalite-black') {
2771
+ previewEl.style.borderColor = '#d4af37';
2772
+ previewEl.style.boxShadow = '0 0 25px rgba(212, 175, 55, 0.35)';
2773
+ } else if (styleInfo.className === 'personnalite-infinite') {
2774
+ previewEl.style.borderColor = '#00c8ff';
2775
+ previewEl.style.boxShadow = '0 0 25px rgba(0, 200, 255, 0.35)';
2776
+ } else if (styleInfo.className === 'ultravioleta-black') {
2777
+ previewEl.style.borderColor = '#a855f7';
2778
+ previewEl.style.boxShadow = '0 0 25px rgba(168, 85, 247, 0.35)';
2779
+ }
2780
+ }
2781
+
2782
+ const fmtLimit = window.formatMoney(limitVal, currency, { locale: 'pt-BR' });
2783
+
2784
+ previewEl.innerHTML = `
2785
+ <div class="card-header-mock">
2786
+ <div class="card-name-mock">${escapeHtml(name)}</div>
2787
+ <div style="font-size:0.75rem; font-weight:700; opacity:0.8; letter-spacing:0.05em;">${brand}</div>
2788
+ </div>
2789
+ <div class="card-number-mock">•••• ${lastDigitsVal}</div>
2790
+ <div class="card-chip"></div>
2791
+ <div class="card-footer-mock">
2792
+ <div>
2793
+ <div class="card-holder-mock">Titular</div>
2794
+ <div class="card-holder-name">RAFAEL F CARNEIRO</div>
2795
+ </div>
2796
+ <div class="card-limit-mock">
2797
+ <div class="card-limit-label">Limite</div>
2798
+ <div class="card-limit-value">${fmtLimit}</div>
2799
+ </div>
2800
+ </div>
2801
+ `;
2802
+ }
2803
+
2804
+ // Edit Credit Card submit
2805
+ async function handleEditCardSubmit(e) {
2806
+ e.preventDefault();
2807
+ if (!activeCard) return;
2808
+
2809
+ const name = document.getElementById('card-edit-name').value;
2810
+ const limit = parseFloat(document.getElementById('card-edit-limit').value);
2811
+ const closing = parseInt(document.getElementById('card-edit-closing-day').value);
2812
+ const due = parseInt(document.getElementById('card-edit-due-day').value);
2813
+ const payAcc = document.getElementById('card-edit-payment-account').value;
2814
+
2815
+ const payload = {
2816
+ limit: limit,
2817
+ closingDay: closing,
2818
+ dueDay: due
2819
+ };
2820
+
2821
+ if (name !== activeCard.name) {
2822
+ payload.newName = name;
2823
+ }
2824
+ if (payAcc) {
2825
+ payload.paymentAccount = payAcc;
2826
+ }
2827
+
2828
+ closeModal('modal-edit-card');
2829
+ billLoading.classList.add('active');
2830
+
2831
+ try {
2832
+ const res = await fetch(`/api/credit-cards/${encodeURIComponent(activeCard.name)}`, {
2833
+ method: 'PATCH',
2834
+ headers: { 'Content-Type': 'application/json' },
2835
+ body: JSON.stringify(payload)
2836
+ });
2837
+
2838
+ if (!res.ok) {
2839
+ const errRes = await res.json();
2840
+ throw new Error(errRes.error?.message || "Falha ao editar cartão de crédito");
2841
+ }
2842
+
2843
+ showToast(`Cartão "${name}" atualizado com sucesso!`, 'success');
2844
+
2845
+ // Reload cards and reselect the updated one
2846
+ await loadCreditCards();
2847
+
2848
+ const updatedCard = creditCards.find(c => c.name === name) || creditCards[0];
2849
+ if (updatedCard) {
2850
+ await selectCard(updatedCard.id);
2851
+ } else {
2852
+ await loadBillDetails();
2853
+ }
2854
+ } catch (err) {
2855
+ console.error("Failed to edit card:", err);
2856
+ showToast(`Erro ao editar cartão: ${err.message}`, 'error');
2857
+ } finally {
2858
+ billLoading.classList.remove('active');
2859
+ }
2860
+ }
2861
+
2862
+ // Load credit cards list
2863
+ async function loadCreditCards() {
2864
+ const res = await fetch('/api/credit-cards');
2865
+ if (res.ok) {
2866
+ creditCards = await res.json();
2867
+ renderCardsCarousel();
2868
+ }
2869
+ }
2870
+
2871
+ // Reassign Bill Modal
2872
+ function openReassignModal(id, desc, date, amount) {
2873
+ document.getElementById('reassign-tx-id').value = id;
2874
+ document.getElementById('reassign-tx-desc').textContent = desc;
2875
+
2876
+ const fmtAmt = window.formatMoney(amount, activeCard.currency, { locale: 'pt-BR' });
2877
+ const dateObj = new Date(date + 'T12:00:00');
2878
+ const dateStr = dateObj.toLocaleDateString('pt-BR');
2879
+ document.getElementById('reassign-tx-details').textContent = `${dateStr} • ${fmtAmt}`;
2880
+
2881
+ const refMonth = parseInt(monthSelect.value);
2882
+ const refYear = parseInt(yearSelect.value);
2883
+
2884
+ const cycleSelect = document.getElementById('reassign-cycle');
2885
+ cycleSelect.innerHTML = '';
2886
+
2887
+ const monthNames = ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"];
2888
+
2889
+ const optionsCycles = [
2890
+ getBillCycleInfo('past', refMonth, refYear),
2891
+ { month: refMonth, year: refYear },
2892
+ getBillCycleInfo('future', refMonth, refYear)
2893
+ ];
2894
+
2895
+ optionsCycles.forEach(cy => {
2896
+ const opt = document.createElement('option');
2897
+ opt.value = `${cy.month}_${cy.year}`;
2898
+ opt.textContent = `${monthNames[cy.month - 1]} ${cy.year}`;
2899
+
2900
+ // Pre-select current target bill of current transaction if known
2901
+ if (currentBill.bill && cy.month === currentBill.bill.month && cy.year === currentBill.bill.year) {
2902
+ opt.selected = true;
2903
+ }
2904
+ cycleSelect.appendChild(opt);
2905
+ });
2906
+
2907
+ openModal('modal-reassign');
2908
+ }
2909
+
2910
+ // Reassign Submit
2911
+ async function handleReassignSubmit(e) {
2912
+ e.preventDefault();
2913
+ const txId = document.getElementById('reassign-tx-id').value;
2914
+ const cycle = document.getElementById('reassign-cycle').value;
2915
+ const parts = cycle.split('_');
2916
+ const month = parseInt(parts[0]);
2917
+ const year = parseInt(parts[1]);
2918
+
2919
+ closeModal('modal-reassign');
2920
+ txLoading.classList.add('active');
2921
+ billLoading.classList.add('active');
2922
+
2923
+ try {
2924
+ const res = await fetch(`/api/credit-cards/transactions/${txId}`, {
2925
+ method: 'PATCH',
2926
+ headers: { 'Content-Type': 'application/json' },
2927
+ body: JSON.stringify({
2928
+ billMonth: month,
2929
+ billYear: year
2930
+ })
2931
+ });
2932
+
2933
+ if (!res.ok) {
2934
+ const errRes = await res.json();
2935
+ throw new Error(errRes.error?.message || "Falha ao mudar fatura");
2936
+ }
2937
+
2938
+ showToast("Fatura do lançamento reatribuída com sucesso!", "success");
2939
+ await loadBillDetails();
2940
+ } catch (err) {
2941
+ console.error("Reassignment error", err);
2942
+ showToast(`Erro ao reatribuir: ${err.message}`, "error");
2943
+ } finally {
2944
+ txLoading.classList.remove('active');
2945
+ billLoading.classList.remove('active');
2946
+ }
2947
+ }
2948
+
2949
+ // Confirm Transaction
2950
+ async function confirmTx(id, description, date, amount) {
2951
+ document.getElementById('confirm-tx-id').value = id;
2952
+ document.getElementById('confirm-tx-desc').textContent = description;
2953
+
2954
+ const dateInput = document.getElementById('confirm-tx-date');
2955
+ const todayStr = new Date().toISOString().split('T')[0];
2956
+
2957
+ if (dateInput._flatpickr) {
2958
+ dateInput._flatpickr.setDate(date || todayStr, true);
2959
+ dateInput._flatpickr.set('maxDate', todayStr);
2960
+ } else {
2961
+ dateInput.value = date || todayStr;
2962
+ dateInput.max = todayStr;
2963
+ }
2964
+
2965
+ applyCurrencyPrecision(['confirm-tx-amount'], activeCard?.currency ?? window.DEFAULT_CURRENCY);
2966
+ document.getElementById('confirm-tx-amount').value = amount || '';
2967
+
2968
+ openModal('modal-confirm-tx');
2969
+ }
2970
+
2971
+ async function handleConfirmSubmit(e) {
2972
+ e.preventDefault();
2973
+ const id = document.getElementById('confirm-tx-id').value;
2974
+ const description = document.getElementById('confirm-tx-desc').textContent;
2975
+ const date = document.getElementById('confirm-tx-date').value;
2976
+ const amount = parseFloat(document.getElementById('confirm-tx-amount').value);
2977
+
2978
+ closeModal('modal-confirm-tx');
2979
+ txLoading.classList.add('active');
2980
+ billLoading.classList.add('active');
2981
+
2982
+ try {
2983
+ const res = await fetch(`/api/transactions/${id}/confirm`, {
2984
+ method: 'POST',
2985
+ headers: { 'Content-Type': 'application/json' },
2986
+ body: JSON.stringify({ date, amount })
2987
+ });
2988
+
2989
+ if (!res.ok) {
2990
+ const errRes = await res.json();
2991
+ throw new Error(errRes.error?.message || "Erro ao confirmar transação");
2992
+ }
2993
+
2994
+ showToast(`Transação "${description}" confirmada com sucesso!`, 'success');
2995
+ await loadBillDetails();
2996
+ } catch (err) {
2997
+ console.error("Confirmation error:", err);
2998
+ showToast(`Erro ao confirmar: ${err.message}`, 'error');
2999
+ } finally {
3000
+ txLoading.classList.remove('active');
3001
+ billLoading.classList.remove('active');
3002
+ }
3003
+ }
3004
+
3005
+ // Delete Transaction
3006
+ async function deleteTx(id, description) {
3007
+ if (!confirm(`Deseja excluir definitivamente o lançamento "${description}"?`)) {
3008
+ return;
3009
+ }
3010
+
3011
+ txLoading.classList.add('active');
3012
+ billLoading.classList.add('active');
3013
+
3014
+ try {
3015
+ const res = await fetch(`/api/credit-cards/transactions/${id}?confirm=true`, {
3016
+ method: 'DELETE'
3017
+ });
3018
+
3019
+ if (!res.ok) throw new Error("Erro ao excluir transação");
3020
+
3021
+ showToast(`Lançamento "${description}" excluído com sucesso!`, 'success');
3022
+ await loadBillDetails();
3023
+ } catch (err) {
3024
+ console.error("Deletion error:", err);
3025
+ showToast(`Erro ao excluir: ${err.message}`, 'error');
3026
+ } finally {
3027
+ txLoading.classList.remove('active');
3028
+ billLoading.classList.remove('active');
3029
+ }
3030
+ }
3031
+
3032
+ // Pay Bill Modal
3033
+ function openPayModal() {
3034
+ if (!currentBill || !activeCard) return;
3035
+
3036
+ document.getElementById('pay-card-name').textContent = activeCard.name;
3037
+
3038
+ const monthNames = ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"];
3039
+ const b = currentBill.bill || {};
3040
+ document.getElementById('pay-bill-cycle').textContent = `Ciclo de Fatura: ${monthNames[b.month - 1]} / ${b.year}`;
3041
+
3042
+ const fmtAmount = window.formatMoney(currentBill.total || 0, activeCard.currency);
3043
+
3044
+ document.getElementById('pay-bill-total').textContent = fmtAmount;
3045
+
3046
+ // Populate account select
3047
+ const accSelect = document.getElementById('pay-account');
3048
+ accSelect.innerHTML = '';
3049
+
3050
+ // Only checking accounts or wallets matching the card's own currency
3051
+ const validAccounts = accounts.filter(a => a.type !== 'credit' && a.currency === activeCard.currency);
3052
+
3053
+ validAccounts.forEach(a => {
3054
+ const opt = document.createElement('option');
3055
+ opt.value = a.name;
3056
+ opt.textContent = `${a.name}`;
3057
+
3058
+ // Pre-select the payment account id match if matching
3059
+ if (activeCard.paymentAccountId === a.id) {
3060
+ opt.selected = true;
3061
+ }
3062
+ accSelect.appendChild(opt);
3063
+ });
3064
+
3065
+ // Pre-fill payment date to today and set max to today
3066
+ const today = new Date();
3067
+ const yyyy = today.getFullYear();
3068
+ const mm = String(today.getMonth() + 1).padStart(2, '0');
3069
+ const dd = String(today.getDate()).padStart(2, '0');
3070
+ const todayStr = `${yyyy}-${mm}-${dd}`;
3071
+ const dateInput = document.getElementById('pay-date');
3072
+ if (dateInput._flatpickr) {
3073
+ dateInput._flatpickr.setDate(todayStr, true);
3074
+ dateInput._flatpickr.set('maxDate', todayStr);
3075
+ } else {
3076
+ dateInput.value = todayStr;
3077
+ dateInput.max = todayStr;
3078
+ }
3079
+
3080
+ openModal('modal-pay-bill');
3081
+ }
3082
+
3083
+ // Pay Bill Submit
3084
+ async function handlePaySubmit(e) {
3085
+ e.preventDefault();
3086
+ if (!currentBill || !activeCard) return;
3087
+
3088
+ const payAccName = document.getElementById('pay-account').value;
3089
+ const payDate = document.getElementById('pay-date').value;
3090
+ const b = currentBill.bill || {};
3091
+
3092
+ closeModal('modal-pay-bill');
3093
+ billLoading.classList.add('active');
3094
+
3095
+ try {
3096
+ const res = await fetch('/api/bills/pay', {
3097
+ method: 'POST',
3098
+ headers: { 'Content-Type': 'application/json' },
3099
+ body: JSON.stringify({
3100
+ card: activeCard.name,
3101
+ month: b.month,
3102
+ year: b.year,
3103
+ account: payAccName,
3104
+ paymentDate: payDate
3105
+ })
3106
+ });
3107
+
3108
+ if (!res.ok) {
3109
+ const errRes = await res.json();
3110
+ throw new Error(errRes.error?.message || "Erro no pagamento");
3111
+ }
3112
+
3113
+ showToast(`Fatura de ${activeCard.name} paga com sucesso!`, 'success');
3114
+ await loadBillDetails();
3115
+ } catch (err) {
3116
+ console.error("Pay bill error", err);
3117
+ showToast(`Erro ao pagar fatura: ${err.message}`, 'error');
3118
+ } finally {
3119
+ billLoading.classList.remove('active');
3120
+ }
3121
+ }
3122
+
3123
+ // Revert Bill Payment
3124
+ async function revertBillPayment() {
3125
+ if (!currentBill || !activeCard) return;
3126
+ const b = currentBill.bill || {};
3127
+
3128
+ if (!confirm(`Deseja realmente reverter o pagamento da fatura de ${activeCard.name} (${b.month}/${b.year})?`)) {
3129
+ return;
3130
+ }
3131
+
3132
+ billLoading.classList.add('active');
3133
+
3134
+ try {
3135
+ const res = await fetch('/api/bills/revert', {
3136
+ method: 'POST',
3137
+ headers: { 'Content-Type': 'application/json' },
3138
+ body: JSON.stringify({
3139
+ card: activeCard.name,
3140
+ month: b.month,
3141
+ year: b.year
3142
+ })
3143
+ });
3144
+
3145
+ if (!res.ok) {
3146
+ const errRes = await res.json();
3147
+ throw new Error(errRes.error?.message || "Erro ao reverter");
3148
+ }
3149
+
3150
+ showToast(`Pagamento da fatura revertido com sucesso!`, 'success');
3151
+ await loadBillDetails();
3152
+ } catch (err) {
3153
+ console.error("Revert payment error", err);
3154
+ showToast(`Erro ao reverter: ${err.message}`, 'error');
3155
+ } finally {
3156
+ billLoading.classList.remove('active');
3157
+ }
3158
+ }
3159
+
3160
+ // HTML escaping
3161
+ function escapeHtml(str) {
3162
+ if (!str) return '';
3163
+ return str.replace(/&/g, "&amp;")
3164
+ .replace(/</g, "&lt;")
3165
+ .replace(/>/g, "&gt;")
3166
+ .replace(/"/g, "&quot;")
3167
+ .replace(/'/g, "&#039;");
3168
+ }
3169
+
3170
+ // JS escaping
3171
+ // Escapes a value for safe embedding as a single-quoted JS string literal *inside* an
3172
+ // HTML attribute (e.g. onclick="fn('${escapeJsAttr(value)}')"). JS-escaping backslash+quote
3173
+ // alone is not enough: the outer onclick="..." attribute is double-quoted, and the HTML
3174
+ // parser (which finds the attribute's closing quote before any JS is parsed) doesn't
3175
+ // understand a JS \" escape — a raw '"' still ends the attribute early. HTML-escaping the
3176
+ // JS-escaped result closes that gap too.
3177
+ function escapeJsAttr(str) {
3178
+ if (!str) return '';
3179
+ return escapeHtml(String(str).replace(/\\/g, '\\\\').replace(/'/g, "\\'"));
3180
+ }
3181
+
3182
+ // Event listeners for month/year change
3183
+ monthSelect.addEventListener('change', async () => {
3184
+ updateTabLabels();
3185
+ await determineDefaultBillType();
3186
+ });
3187
+ yearSelect.addEventListener('change', async () => {
3188
+ updateTabLabels();
3189
+ await determineDefaultBillType();
3190
+ });
3191
+
3192
+ // Bootstrap App
3193
+
3194
+ // Translation engine and dictionaries
3195
+ var TRANSLATIONS = {
3196
+ en: {
3197
+ // Sidebar Menu
3198
+ tooltip_overview: "Overview",
3199
+ tooltip_pending: "Pending",
3200
+ tooltip_comparative: "Comparative",
3201
+ tooltip_projections: "Projections",
3202
+ tooltip_accounts: "Bank Accounts",
3203
+ tooltip_cards: "Credit Cards",
3204
+ menu_categories: "Categories",
3205
+ menu_dashboards: "Dashboards",
3206
+
3207
+ // Month names
3208
+ january: "January", february: "February", march: "March", april: "April", may: "May", june: "June",
3209
+ july: "July", august: "August", september: "September", october: "October", november: "November", december: "December",
3210
+
3211
+ // General UI terms
3212
+ reference_label: "Reference:",
3213
+ day_sun: "Sun", day_mon: "Mon", day_tue: "Tue", day_wed: "Wed", day_thu: "Thu", day_fri: "Fri", day_sat: "Sat",
3214
+ paid: "Paid", unpaid: "Unpaid", active: "Active", inactive: "Inactive",
3215
+
3216
+ // Overview Dashboard
3217
+ overview_title: "Overview",
3218
+ overview_subtitle: "Monthly financial summary, calendar, and quick shortcuts",
3219
+ accounts_balance: "Accounts Balance",
3220
+ expenses_month: "Expenses this Month",
3221
+ card_bills: "Credit Card Bills",
3222
+ incomes_month: "Incomes this Month",
3223
+ final_projection: "Final Projection:",
3224
+ recent_transactions: "Recent Transactions",
3225
+ due_calendar: "Daily Flow & Dues",
3226
+ expenses_distribution: "Expenses Distribution",
3227
+ quick_shortcuts: "Quick Shortcuts",
3228
+ new_transaction: "New Transaction",
3229
+ new_transfer: "New Transfer",
3230
+ new_category: "New Category",
3231
+ new_card: "New Card",
3232
+ new_account: "New Account",
3233
+ no_expenses_month: "No expenses recorded this month.",
3234
+ no_recent_transactions: "No recent transactions found.",
3235
+ no_dues_period: "No transactions due in this period.",
3236
+ income: "Income",
3237
+ expense: "Expense",
3238
+ paid_reconciled: "Paid / Reconciled",
3239
+
3240
+ // Projections / Heatmap Dashboard
3241
+ projections_title: "Recurring & Installment Projections",
3242
+ projections_subtitle: "Advanced visual mapping and projection of active recurrences and installments for the next months",
3243
+ projection_label: "Projection:",
3244
+ months_3: "3 Months",
3245
+ months_6: "6 Months",
3246
+ months_9: "9 Months",
3247
+ months_12: "12 Months",
3248
+ heatmap_income_title: "Recurrent / Installment Incomes",
3249
+ heatmap_expense_title: "Recurrent / Installment Expenses",
3250
+ total: "Total",
3251
+ no_recurrent_incomes: "No active recurrent or installment incomes in the selected semester.",
3252
+ no_recurrent_expenses: "No active recurrent or installment expenses in the selected semester.",
3253
+ modal_details_title: "Projection Breakdown",
3254
+ modal_details_subtitle: "Details of projected transactions for the category and month",
3255
+ col_date: "Date",
3256
+ col_desc: "Description",
3257
+ col_value: "Value",
3258
+ col_status: "Status",
3259
+ btn_close: "Close",
3260
+
3261
+ // Comparative Dashboard
3262
+ comparative_title: "Comparative Dashboard",
3263
+ comparative_subtitle: "Analysis and comparison of monthly incomes vs expenses, and category limits",
3264
+ month_summary_title: "Month Summary",
3265
+ cat_spending_title: "Spending by Category",
3266
+ card_limits_title: "Category Budgets & Limits",
3267
+ col_category: "Category",
3268
+ col_limit: "Budget Limit",
3269
+ col_spent: "Spent",
3270
+ col_status_limit: "Status",
3271
+ col_percentage: "Percentage",
3272
+ within_limit: "Within Limit",
3273
+ exceeded: "Exceeded",
3274
+ reception: "Incomes",
3275
+ deduction: "Expenses",
3276
+ net_balance: "Net Balance",
3277
+ performance: "Financial Health",
3278
+ no_spending_month: "No category spend recorded this month.",
3279
+
3280
+ // Accounts Dashboard
3281
+ accounts_title: "Bank Accounts",
3282
+ accounts_subtitle: "Manage accounts, checking balances, and reviewing statements",
3283
+ active_account_statement: "Account Statement",
3284
+ btn_new_transaction: "New Transaction",
3285
+ btn_new_transfer: "New Transfer",
3286
+ search_description_placeholder: "Type to search...",
3287
+ filter_type_label: "Type",
3288
+ filter_type_all: "All",
3289
+ filter_type_income: "Incomes",
3290
+ filter_type_expense: "Expenses",
3291
+ col_actions: "Actions",
3292
+ action_confirm: "Confirm",
3293
+ action_edit: "Edit",
3294
+ action_delete: "Delete",
3295
+ no_transactions_account: "No transactions recorded for this account in the selected month.",
3296
+ confirm_delete_title: "Are you sure you want to permanently delete this transaction?",
3297
+ modal_new_tx_title: "New Transaction",
3298
+ modal_new_transfer_title: "New Transfer",
3299
+ label_account: "Account",
3300
+ label_description: "Description",
3301
+ label_value: "Value",
3302
+ label_date: "Date",
3303
+ label_category: "Category / Subcategory",
3304
+ label_type: "Type",
3305
+ label_status: "Status",
3306
+ status_pending: "Pending",
3307
+ status_confirmed: "Paid / Confirmed",
3308
+ btn_cancel: "Cancel",
3309
+ btn_save: "Save",
3310
+ label_origin: "Origin Account",
3311
+ label_destination: "Destination Account",
3312
+ modal_confirm_tx_title: "Confirm Transaction",
3313
+ label_confirm_date: "Confirmation Date",
3314
+ btn_edit_card: "Edit Card",
3315
+ btn_create_card: "Create Card",
3316
+ modal_add_card_title: "New Credit Card",
3317
+ modal_edit_card_title: "Edit Credit Card",
3318
+ label_card_name: "Card Name",
3319
+ label_closing_day: "Closing Day",
3320
+ label_due_day: "Due Day",
3321
+ label_currency: "Currency",
3322
+ label_payment_account: "Default Paying Account",
3323
+ design_preview: "Design Preview",
3324
+
3325
+ // Pending Dashboard
3326
+ pending_title: "Pending Transactions",
3327
+ pending_subtitle: "Monitoring and quick confirmation of pending or future transactions",
3328
+ pending_kpi_total: "Total Pending",
3329
+ pending_kpi_incomes: "Pending Incomes",
3330
+ pending_kpi_expenses: "Pending Expenses",
3331
+ pending_chart_incomes: "Pending Incomes Trend",
3332
+ pending_chart_expenses: "Pending Expenses Trend",
3333
+ btn_confirm: "Confirm",
3334
+ btn_edit: "Edit",
3335
+ btn_delete: "Delete",
3336
+ no_pending_transactions: "No pending transactions found for this period.",
3337
+ toast_success_confirm: "Transaction confirmed successfully!",
3338
+
3339
+ // Categories Dashboard
3340
+ categories_title: "Category Management",
3341
+ categories_subtitle: "Visualize, search, and manage categories and subcategories in a clean tree list",
3342
+ btn_new_category: "New Category",
3343
+ search_category_placeholder: "Search categories...",
3344
+ col_type: "Type",
3345
+ col_actions_cat: "Actions",
3346
+ subcategories_label: "Subcategories",
3347
+ no_subcategories: "No subcategories registered.",
3348
+ modal_new_cat_title: "New Category",
3349
+ modal_new_subcat_title: "New Subcategory",
3350
+ label_name: "Name",
3351
+ label_color: "Color",
3352
+ label_parent_category: "Parent Category (Read-Only)",
3353
+ toast_success_cat: "Category created successfully!",
3354
+ toast_success_subcat: "Subcategory created successfully!",
3355
+
3356
+ // Cards Dashboard
3357
+ cards_title: "Credit Cards",
3358
+ cards_subtitle: "Manage credit cards, credit limits, and statement history",
3359
+ card_bill_details: "Card Bill Details",
3360
+ btn_pay_bill: "Pay Bill",
3361
+ btn_revert_payment: "Revert Payment",
3362
+ bill_status: "Bill Status:",
3363
+ status_open: "Open",
3364
+ status_closed: "Closed",
3365
+ status_paid: "Paid",
3366
+ no_card_transactions: "No transactions recorded for this card bill in the selected cycle.",
3367
+
3368
+ // Dashboards Manager Dashboard
3369
+ dashboards_title: "Dashboards Monitor",
3370
+ dashboards_subtitle: "List, view source, and upload patty dashboards",
3371
+ col_dashboard: "Dashboard",
3372
+ col_last_update: "Last Updated",
3373
+ btn_view_source: "View Source",
3374
+ btn_download: "Download",
3375
+ upload_new_dashboard: "Upload New Dashboard",
3376
+ placeholder_dashboard_name: "Dashboard Name (e.g. pending)",
3377
+ upload_instructions: "Select or drop HTML file here to upload",
3378
+ btn_upload: "Upload",
3379
+ modal_source_title: "HTML Source Code",
3380
+
3381
+ // Tags Management
3382
+ menu_tags: "Tags",
3383
+ tags_title: "Tag Management",
3384
+ tags_subtitle: "Manage tags to label and organize your transactions",
3385
+ panel_title_tags: "Active Tags",
3386
+ btn_new_tag: "New Tag",
3387
+ label_tag_name: "Tag Name",
3388
+ placeholder_tag_name: "E.g. work, travel, refund",
3389
+ empty_tags_message: "No tags registered.",
3390
+ btn_save: "Save",
3391
+ btn_cancel: "Cancel",
3392
+ toast_success_tag_created: 'Tag "{name}" created successfully!',
3393
+ toast_success_tag_deleted: 'Tag "{name}" deleted successfully!',
3394
+ confirm_delete_tag: 'Are you sure you want to delete tag "{name}"?\n(This action will remove the tag from all linked transactions)'
3395
+ },
3396
+ pt: {
3397
+ // Sidebar Menu
3398
+ tooltip_overview: "Visão Geral",
3399
+ tooltip_pending: "Pendentes",
3400
+ tooltip_comparative: "Comparativo",
3401
+ tooltip_projections: "Projeções",
3402
+ tooltip_accounts: "Contas Bancárias",
3403
+ tooltip_cards: "Cartões de Crédito",
3404
+ menu_categories: "Categorias",
3405
+ menu_dashboards: "Dashboards",
3406
+
3407
+ // Month names
3408
+ january: "Janeiro", february: "Fevereiro", march: "Março", april: "Abril", may: "Maio", june: "Junho",
3409
+ july: "Julho", august: "Agosto", september: "Setembro", october: "Outubro", november: "Novembro", december: "Dezembro",
3410
+
3411
+ // General UI terms
3412
+ reference_label: "Referência:",
3413
+ day_sun: "Dom", day_mon: "Seg", day_tue: "Ter", day_wed: "Qua", day_thu: "Qui", day_fri: "Sex", day_sat: "Sáb",
3414
+ paid: "Pago", unpaid: "Não Pago", active: "Ativo", inactive: "Inativo",
3415
+
3416
+ // Overview Dashboard
3417
+ overview_title: "Visão Geral",
3418
+ overview_subtitle: "Consolidado financeiro mensal, calendário e atalhos rápidos",
3419
+ accounts_balance: "Saldo em Contas",
3420
+ expenses_month: "Despesas do Mês",
3421
+ card_bills: "Faturas de Cartão",
3422
+ incomes_month: "Receitas do Mês",
3423
+ final_projection: "Projeção Final:",
3424
+ recent_transactions: "Lançamentos Recentes",
3425
+ due_calendar: "Fluxo Diário",
3426
+ expenses_distribution: "Distribuição de Despesas",
3427
+ quick_shortcuts: "Atalhos Rápidos",
3428
+ new_transaction: "Novo Lançamento",
3429
+ new_transfer: "Nova Transferência",
3430
+ new_category: "Nova Categoria",
3431
+ new_card: "Novo Cartão",
3432
+ new_account: "Nova Conta",
3433
+ no_expenses_month: "Sem despesas registradas neste mês.",
3434
+ no_recent_transactions: "Nenhuma transação recente encontrada.",
3435
+ no_dues_period: "Sem vencimentos neste período.",
3436
+ income: "Receita",
3437
+ expense: "Despesa",
3438
+ paid_reconciled: "Pago / Conciliado",
3439
+
3440
+ // Projections / Heatmap Dashboard
3441
+ projections_title: "Projeção de Recorrências e Parcelas",
3442
+ projections_subtitle: "Mapeamento visual avançado e projeção de recorrências e parcelas ativas para os próximos meses",
3443
+ projection_label: "Projeção:",
3444
+ months_3: "3 Meses",
3445
+ months_6: "6 Meses",
3446
+ months_9: "9 Meses",
3447
+ months_12: "12 Meses",
3448
+ heatmap_income_title: "Receitas Recorrentes / Parceladas",
3449
+ heatmap_expense_title: "Despesas Recorrentes / Parceladas",
3450
+ total: "Total",
3451
+ no_recurrent_incomes: "Nenhuma receita recorrente/parcelada ativa no semestre.",
3452
+ no_recurrent_expenses: "Nenhuma despesa recorrente/parcelada ativa no semestre.",
3453
+ modal_details_title: "Detalhamento de Projeções",
3454
+ modal_details_subtitle: "Detalhes das transações projetadas para a categoria e mês",
3455
+ col_date: "Data",
3456
+ col_desc: "Descrição",
3457
+ col_value: "Valor",
3458
+ col_status: "Status",
3459
+ btn_close: "Fechar",
3460
+
3461
+ // Comparative Dashboard
3462
+ comparative_title: "Dashboard Comparativo",
3463
+ comparative_subtitle: "Análise e comparação mensal de receitas vs despesas e limites por categoria",
3464
+ month_summary_title: "Resumo do Mês",
3465
+ cat_spending_title: "Gastos por Categoria",
3466
+ card_limits_title: "Orçamentos e Limites de Categorias",
3467
+ col_category: "Categoria",
3468
+ col_limit: "Limite de Orçamento",
3469
+ col_spent: "Gasto",
3470
+ col_status_limit: "Status",
3471
+ col_percentage: "Porcentagem",
3472
+ within_limit: "Dentro do Limite",
3473
+ exceeded: "Excedido",
3474
+ reception: "Receitas",
3475
+ deduction: "Despesas",
3476
+ net_balance: "Saldo Líquido",
3477
+ performance: "Saúde Financeira",
3478
+ no_spending_month: "Sem despesas registradas por categoria neste mês.",
3479
+
3480
+ // Accounts Dashboard
3481
+ accounts_title: "Minhas Contas",
3482
+ accounts_subtitle: "Gerencie contas, consulte saldos e revise extratos",
3483
+ active_account_statement: "Extrato de Conta",
3484
+ btn_new_transaction: "Novo Lançamento",
3485
+ btn_new_transfer: "Nova Transferência",
3486
+ search_description_placeholder: "Digite para filtrar...",
3487
+ filter_type_label: "Tipo",
3488
+ filter_type_all: "Todos",
3489
+ filter_type_income: "Receitas",
3490
+ filter_type_expense: "Despesas",
3491
+ col_actions: "Ações",
3492
+ action_confirm: "Confirmar",
3493
+ action_edit: "Editar",
3494
+ action_delete: "Excluir",
3495
+ no_transactions_account: "Nenhum lançamento nesta conta para o mês selecionado.",
3496
+ confirm_delete_title: "Deseja excluir definitivamente a transação?",
3497
+ modal_new_tx_title: "Novo Lançamento",
3498
+ modal_new_transfer_title: "Nova Transferência",
3499
+ label_account: "Conta",
3500
+ label_description: "Descrição",
3501
+ label_value: "Valor",
3502
+ label_date: "Data",
3503
+ label_category: "Categoria / Subcategoria",
3504
+ label_type: "Tipo",
3505
+ label_status: "Status",
3506
+ status_pending: "Pendente",
3507
+ status_confirmed: "Pago / Confirmado",
3508
+ btn_cancel: "Cancelar",
3509
+ btn_save: "Salvar",
3510
+ label_origin: "Conta Origem",
3511
+ label_destination: "Conta Destino",
3512
+ modal_confirm_tx_title: "Confirmar Lançamento",
3513
+ label_confirm_date: "Data da Confirmação",
3514
+ btn_edit_card: "Editar Cartão",
3515
+ btn_create_card: "Criar Cartão",
3516
+ modal_add_card_title: "Novo Cartão de Crédito",
3517
+ modal_edit_card_title: "Editar Cartão de Crédito",
3518
+ label_card_name: "Nome do Cartão",
3519
+ label_closing_day: "Fechamento",
3520
+ label_due_day: "Vencimento",
3521
+ label_currency: "Moeda",
3522
+ label_payment_account: "Conta Padrão",
3523
+ design_preview: "Pré-visualização do Design",
3524
+
3525
+ // Pending Dashboard
3526
+ pending_title: "Transações Pendentes",
3527
+ pending_subtitle: "Monitoramento e confirmação rápida de lançamentos pendentes ou futuros",
3528
+ pending_kpi_total: "Total Pendente",
3529
+ pending_kpi_incomes: "Receitas Pendentes",
3530
+ pending_kpi_expenses: "Despesas Pendentes",
3531
+ pending_chart_incomes: "Tendência de Receitas Pendentes",
3532
+ pending_chart_expenses: "Tendência de Despesas Pendentes",
3533
+ btn_confirm: "Confirmar",
3534
+ btn_edit: "Editar",
3535
+ btn_delete: "Excluir",
3536
+ no_pending_transactions: "Nenhuma transação pendente encontrada para este período.",
3537
+ toast_success_confirm: "Transação confirmada com sucesso!",
3538
+
3539
+ // Categories Dashboard
3540
+ categories_title: "Gerenciamento de Categorias",
3541
+ categories_subtitle: "Visualize, pesquise e gerencie categorias e subcategorias em árvore",
3542
+ btn_new_category: "Nova Categoria",
3543
+ search_category_placeholder: "Pesquisar categorias...",
3544
+ col_type: "Tipo",
3545
+ col_actions_cat: "Ações",
3546
+ subcategories_label: "Subcategorias",
3547
+ no_subcategories: "Nenhuma subcategoria cadastrada.",
3548
+ modal_new_cat_title: "Nova Categoria",
3549
+ modal_new_subcat_title: "Nova Subcategoria",
3550
+ label_name: "Nome",
3551
+ label_color: "Cor",
3552
+ label_parent_category: "Categoria Pai (Somente Leitura)",
3553
+ toast_success_cat: "Categoria criada com sucesso!",
3554
+ toast_success_subcat: "Subcategoria criada com sucesso!",
3555
+
3556
+ // Cards Dashboard
3557
+ cards_title: "Cartões de Crédito",
3558
+ cards_subtitle: "Gerencie cartões de crédito, limites e histórico de faturas",
3559
+ card_bill_details: "Detalhamento de Fatura",
3560
+ btn_pay_bill: "Pagar Fatura",
3561
+ btn_revert_payment: "Estornar Pagamento",
3562
+ bill_status: "Status da Fatura:",
3563
+ status_open: "Aberta",
3564
+ status_closed: "Fechada",
3565
+ status_paid: "Paga",
3566
+ no_card_transactions: "Nenhuma transação registrada nesta fatura para o ciclo selecionado.",
3567
+
3568
+ // Dashboards Manager Dashboard
3569
+ dashboards_title: "Monitor de Dashboards",
3570
+ dashboards_subtitle: "Liste, visualize o código fonte e envie dashboards para o servidor do patty",
3571
+ col_dashboard: "Dashboard",
3572
+ col_last_update: "Última Atualização",
3573
+ btn_view_source: "Ver Código",
3574
+ btn_download: "Baixar HTML",
3575
+ upload_new_dashboard: "Enviar Novo Dashboard",
3576
+ placeholder_dashboard_name: "Nome do Dashboard (ex: pending)",
3577
+ upload_instructions: "Selecione ou solte o arquivo HTML aqui para upload",
3578
+ btn_upload: "Fazer Upload",
3579
+ modal_source_title: "Código Fonte HTML",
3580
+
3581
+ // Tags Management
3582
+ menu_tags: "Tags",
3583
+ tags_title: "Gerenciar Tags",
3584
+ tags_subtitle: "Gerencie as tags utilizadas para rotular e categorizar suas transações",
3585
+ panel_title_tags: "Tags Ativas",
3586
+ btn_new_tag: "Nova Tag",
3587
+ label_tag_name: "Nome da Tag",
3588
+ placeholder_tag_name: "Ex: trabalho, viagem, reembolso",
3589
+ empty_tags_message: "Nenhuma tag cadastrada.",
3590
+ btn_save: "Salvar",
3591
+ btn_cancel: "Cancelar",
3592
+ toast_success_tag_created: 'Tag "{name}" criada com sucesso!',
3593
+ toast_success_tag_deleted: 'Tag "{name}" excluída com sucesso!',
3594
+ confirm_delete_tag: 'Deseja realmente excluir a tag "{name}"?\n(Esta ação removerá a tag de todas as transações vinculadas)'
3595
+ },
3596
+ es: {
3597
+ // Sidebar Menu
3598
+ tooltip_overview: "Vista General",
3599
+ tooltip_pending: "Pendientes",
3600
+ tooltip_comparative: "Comparativo",
3601
+ tooltip_projections: "Proyecciones",
3602
+ tooltip_accounts: "Cuentas Bancárias",
3603
+ tooltip_cards: "Tarjetas de Crédito",
3604
+ menu_categories: "Categorías",
3605
+ menu_dashboards: "Dashboards",
3606
+
3607
+ // Month names
3608
+ january: "Enero", february: "Febrero", march: "Marzo", april: "Abril", may: "Mayo", june: "Junio",
3609
+ july: "Julio", august: "Agosto", september: "Septiembre", october: "Octubre", november: "Noviembre", december: "Diciembre",
3610
+
3611
+ // General UI terms
3612
+ reference_label: "Referencia:",
3613
+ day_sun: "Dom", day_mon: "Lun", day_tue: "Mar", day_wed: "Mié", day_thu: "Jue", day_fri: "Vie", day_sat: "Sáb",
3614
+ paid: "Pagado", unpaid: "No Pagado", active: "Activo", inactive: "Inactivo",
3615
+
3616
+ // Overview Dashboard
3617
+ overview_title: "Vista General",
3618
+ overview_subtitle: "Resumen financiero mensual, calendario y accesos rápidos",
3619
+ accounts_balance: "Saldo en Cuentas",
3620
+ expenses_month: "Gastos del Mes",
3621
+ card_bills: "Facturas de Tarjeta",
3622
+ incomes_month: "Ingresos del Mes",
3623
+ final_projection: "Proyección Final:",
3624
+ recent_transactions: "Transacciones Recientes",
3625
+ due_calendar: "Calendario de Pagos",
3626
+ expenses_distribution: "Distribución de Gastos",
3627
+ quick_shortcuts: "Accesos Rápidos",
3628
+ new_transaction: "Nueva Transacción",
3629
+ new_transfer: "Nueva Transferencia",
3630
+ new_category: "Nueva Categoría",
3631
+ new_card: "Nueva Tarjeta",
3632
+ new_account: "Nueva Cuenta",
3633
+ no_expenses_month: "No hay gastos registrados este mes.",
3634
+ no_recent_transactions: "No se encontraron transacciones recientes.",
3635
+ no_dues_period: "Sin vencimientos en este período.",
3636
+ income: "Ingreso",
3637
+ expense: "Gasto",
3638
+ paid_reconciled: "Pagado / Conciliado",
3639
+
3640
+ // Projections / Heatmap Dashboard
3641
+ projections_title: "Proyección de Recurrencias y Cuotas",
3642
+ projections_subtitle: "Mapeo visual avanzado y proyección de recurrencias y cuotas activas para los próximos meses",
3643
+ projection_label: "Proyección:",
3644
+ months_3: "3 Meses",
3645
+ months_6: "6 Meses",
3646
+ months_9: "9 Meses",
3647
+ months_12: "12 Meses",
3648
+ heatmap_income_title: "Ingresos Recurrentes / Cuotas",
3649
+ heatmap_expense_title: "Gastos Recurrentes / Cuotas",
3650
+ total: "Total",
3651
+ no_recurrent_incomes: "Ningún ingreso recurrente o en cuotas activo en el semestre seleccionado.",
3652
+ no_recurrent_expenses: "Ningún gasto recurrente o en cuotas activo en el semestre seleccionado.",
3653
+ modal_details_title: "Detalle de Proyecciones",
3654
+ modal_details_subtitle: "Detalles de transacciones proyectadas para la categoría y mes",
3655
+ col_date: "Fecha",
3656
+ col_desc: "Descripción",
3657
+ col_value: "Valor",
3658
+ col_status: "Estado",
3659
+ btn_close: "Cerrar",
3660
+
3661
+ // Comparative Dashboard
3662
+ comparative_title: "Dashboard Comparativo",
3663
+ comparative_subtitle: "Análisis y comparación mensual de ingresos vs gastos y límites por categoría",
3664
+ month_summary_title: "Resumen del Mes",
3665
+ cat_spending_title: "Gastos por Categoría",
3666
+ card_limits_title: "Presupuestos y Límites de Categorías",
3667
+ col_category: "Categoría",
3668
+ col_limit: "Límite de Presupuesto",
3669
+ col_spent: "Gastado",
3670
+ col_status_limit: "Estado",
3671
+ col_percentage: "Porcentaje",
3672
+ within_limit: "Dentro del Límite",
3673
+ exceeded: "Excedido",
3674
+ reception: "Ingresos",
3675
+ deduction: "Gastos",
3676
+ net_balance: "Saldo Neto",
3677
+ performance: "Salud Financiera",
3678
+ no_spending_month: "No hay gastos registrados por categoría este mes.",
3679
+
3680
+ // Accounts Dashboard
3681
+ accounts_title: "Cuentas Bancarias",
3682
+ accounts_subtitle: "Administre cuentas, consulte saldos y revise extractos",
3683
+ active_account_statement: "Extracto de Cuenta",
3684
+ btn_new_transaction: "Nueva Transacción",
3685
+ btn_new_transfer: "Nueva Transferencia",
3686
+ search_description_placeholder: "Escriba para filtrar...",
3687
+ filter_type_label: "Tipo",
3688
+ filter_type_all: "Todos",
3689
+ filter_type_income: "Ingresos",
3690
+ filter_type_expense: "Gastos",
3691
+ col_actions: "Acciones",
3692
+ action_confirm: "Confirmar",
3693
+ action_edit: "Editar",
3694
+ action_delete: "Eliminar",
3695
+ no_transactions_account: "No hay transacciones registradas en esta cuenta en el mes seleccionado.",
3696
+ confirm_delete_title: "¿Está seguro de eliminar definitivamente esta transacción?",
3697
+ modal_new_tx_title: "Nueva Transacción",
3698
+ modal_new_transfer_title: "Nueva Transferencia",
3699
+ label_account: "Cuenta",
3700
+ label_description: "Descripción",
3701
+ label_value: "Valor",
3702
+ label_date: "Fecha",
3703
+ label_category: "Categoría / Subcategoría",
3704
+ label_type: "Tipo",
3705
+ label_status: "Estado",
3706
+ status_pending: "Pendiente",
3707
+ status_confirmed: "Pagado / Confirmado",
3708
+ btn_cancel: "Cancelar",
3709
+ btn_save: "Guardar",
3710
+ label_origin: "Cuenta Origen",
3711
+ label_destination: "Cuenta Destino",
3712
+ modal_confirm_tx_title: "Confirmar Transacción",
3713
+ label_confirm_date: "Fecha de Confirmación",
3714
+ btn_edit_card: "Editar Tarjeta",
3715
+ btn_create_card: "Crear Tarjeta",
3716
+ modal_add_card_title: "Nueva Tarjeta de Crédito",
3717
+ modal_edit_card_title: "Editar Tarjeta de Crédito",
3718
+ label_card_name: "Nombre de la Tarjeta",
3719
+ label_closing_day: "Corte",
3720
+ label_due_day: "Vencimiento",
3721
+ label_currency: "Moneda",
3722
+ label_payment_account: "Cuenta Principal",
3723
+ design_preview: "Vista Previa de Diseño",
3724
+
3725
+ // Pending Dashboard
3726
+ pending_title: "Transacciones Pendientes",
3727
+ pending_subtitle: "Monitoreo y confirmación rápida de transacciones pendientes o futuras",
3728
+ pending_kpi_total: "Total Pendiente",
3729
+ pending_kpi_incomes: "Ingresos Pendientes",
3730
+ pending_kpi_expenses: "Gastos Pendientes",
3731
+ pending_chart_incomes: "Tendencia de Ingresos Pendientes",
3732
+ pending_chart_expenses: "Tendencia de Gastos Pendientes",
3733
+ btn_confirm: "Confirmar",
3734
+ btn_edit: "Editar",
3735
+ btn_delete: "Eliminar",
3736
+ no_pending_transactions: "No se encontraron transacciones pendientes en este período.",
3737
+ toast_success_confirm: "¡Transacción confirmada con éxito!",
3738
+
3739
+ // Categories Dashboard
3740
+ categories_title: "Gestión de Categorías",
3741
+ categories_subtitle: "Visualice, busque y gestione categorías y subcategorías en árbol",
3742
+ btn_new_category: "Nueva Categoría",
3743
+ search_category_placeholder: "Buscar categorías...",
3744
+ col_type: "Tipo",
3745
+ col_actions_cat: "Acciones",
3746
+ subcategories_label: "Subcategorías",
3747
+ no_subcategories: "Ninguna subcategoría registrada.",
3748
+ modal_new_cat_title: "Nueva Categoría",
3749
+ modal_new_subcat_title: "Nueva Subcategoría",
3750
+ label_name: "Nombre",
3751
+ label_color: "Color",
3752
+ label_parent_category: "Categoría Padre (Solo Lectura)",
3753
+ toast_success_cat: "¡Categoría creada con éxito!",
3754
+ toast_success_subcat: "¡Subcategoría creada con éxito!",
3755
+
3756
+ // Cards Dashboard
3757
+ cards_title: "Tarjetas de Crédito",
3758
+ cards_subtitle: "Gestione tarjetas de crédito, límites y facturas",
3759
+ card_bill_details: "Detalle de Factura",
3760
+ btn_pay_bill: "Pagar Factura",
3761
+ btn_revert_payment: "Revertir Pago",
3762
+ bill_status: "Estado de la Factura:",
3763
+ status_open: "Abierta",
3764
+ status_closed: "Cerrada",
3765
+ status_paid: "Pagada",
3766
+ no_card_transactions: "Ninguna transacción registrada en esta factura para el ciclo seleccionado.",
3767
+
3768
+ // Dashboards Manager Dashboard
3769
+ dashboards_title: "Gestor de Dashboards",
3770
+ dashboards_subtitle: "Liste, vea el código fuente y suba dashboards al servidor de patty",
3771
+ col_dashboard: "Dashboard",
3772
+ col_last_update: "Última Actualización",
3773
+ btn_view_source: "Ver Código",
3774
+ btn_download: "Descargar HTML",
3775
+ upload_new_dashboard: "Subir Nuevo Dashboard",
3776
+ placeholder_dashboard_name: "Nombre del Dashboard (ej: pending)",
3777
+ upload_instructions: "Seleccione o arrastre el archivo HTML aquí para subir",
3778
+ btn_upload: "Subir Dashboard",
3779
+ modal_source_title: "Código Fuente HTML",
3780
+
3781
+ // Tags Management
3782
+ menu_tags: "Etiquetas",
3783
+ tags_title: "Administrar Etiquetas",
3784
+ tags_subtitle: "Administre las etiquetas utilizadas para etiquetar y organizar sus transacciones",
3785
+ panel_title_tags: "Etiquetas Activas",
3786
+ btn_new_tag: "Nueva Etiqueta",
3787
+ label_tag_name: "Nombre de la Etiqueta",
3788
+ placeholder_tag_name: "Ej: trabajo, viaje, reembolso",
3789
+ empty_tags_message: "No hay etiquetas registradas.",
3790
+ btn_save: "Guardar",
3791
+ btn_cancel: "Cancelar",
3792
+ toast_success_tag_created: '¡Etiqueta "{name}" creada con éxito!',
3793
+ toast_success_tag_deleted: '¡Etiqueta "{name}" eliminada con éxito!',
3794
+ confirm_delete_tag: '¿Realmente deseja eliminar la etiqueta "{name}"?\n(Esta acción eliminará la etiqueta de todas las transacciones vinculadas)'
3795
+ }
3796
+ };
3797
+
3798
+ var currentLocale = 'en'; // English as default
3799
+
3800
+ // Helper to translate in JS
3801
+ function t(key) {
3802
+ const tDict = TRANSLATIONS[currentLocale] || TRANSLATIONS['en'];
3803
+ return tDict[key] || key;
3804
+ }
3805
+
3806
+ async function checkLocale() {
3807
+ try {
3808
+ const res = await fetch('/api/status');
3809
+ if (res.ok) {
3810
+ const data = await res.json();
3811
+ if (data.locale && TRANSLATIONS[data.locale]) {
3812
+ currentLocale = data.locale;
3813
+ }
3814
+ }
3815
+ } catch (err) {
3816
+ console.error("Failed to read locale preferences:", err);
3817
+ }
3818
+ translatePage();
3819
+ }
3820
+
3821
+ function translatePage() {
3822
+ const tDict = TRANSLATIONS[currentLocale] || TRANSLATIONS['en'];
3823
+
3824
+ // 1. Static texts
3825
+ document.querySelectorAll('[data-i18n]').forEach(el => {
3826
+ const key = el.getAttribute('data-i18n');
3827
+ if (tDict[key]) {
3828
+ const icon = el.querySelector('i');
3829
+ if (icon) {
3830
+ const iconOuter = icon.outerHTML;
3831
+ el.innerHTML = iconOuter + ' ' + tDict[key];
3832
+ } else {
3833
+ el.textContent = tDict[key];
3834
+ }
3835
+ }
3836
+ });
3837
+
3838
+ // 2. Placeholders
3839
+ document.querySelectorAll('[data-i18n-placeholder]').forEach(el => {
3840
+ const key = el.getAttribute('data-i18n-placeholder');
3841
+ if (tDict[key]) {
3842
+ el.placeholder = tDict[key];
3843
+ }
3844
+ });
3845
+
3846
+ // 3. Tooltips
3847
+ document.querySelectorAll('[data-i18n-tooltip]').forEach(el => {
3848
+ const key = el.getAttribute('data-i18n-tooltip');
3849
+ if (tDict[key]) {
3850
+ el.setAttribute('data-tooltip', tDict[key]);
3851
+ }
3852
+ });
3853
+
3854
+ // 4. Document title translation
3855
+ if (tDict['overview_title'] && document.title.includes("Overview") || document.title.includes("Visão")) {
3856
+ // dynamic title update fallback if needed
3857
+ }
3858
+
3859
+ // 5. Translate select months
3860
+ const monthSelects = [
3861
+ document.getElementById('month-select'),
3862
+ document.getElementById('start-month-select')
3863
+ ];
3864
+ monthSelects.forEach(monthSelect => {
3865
+ if (monthSelect) {
3866
+ const monthKeys = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
3867
+ Array.from(monthSelect.options).forEach((opt, idx) => {
3868
+ const key = monthKeys[idx];
3869
+ if (tDict[key]) {
3870
+ opt.textContent = tDict[key];
3871
+ }
3872
+ });
3873
+ }
3874
+ });
3875
+
3876
+ // 6. Translate projection months select options (3, 6, 9, 12 months)
3877
+ const hmSelect = document.getElementById('heatmap-months-select');
3878
+ if (hmSelect) {
3879
+ Array.from(hmSelect.options).forEach(opt => {
3880
+ const val = opt.value;
3881
+ const key = `months_${val}`;
3882
+ if (tDict[key]) {
3883
+ opt.textContent = tDict[key];
3884
+ }
3885
+ });
3886
+ }
3887
+
3888
+ // Automatically initialize/refresh custom selects on all pages
3889
+ if (typeof initCustomSelects === 'function') {
3890
+ initCustomSelects();
3891
+ }
3892
+ }
3893
+
3894
+ // Custom Select Component implementation
3895
+ function initCustomSelects() {
3896
+ document.querySelectorAll('select.select-custom').forEach(select => {
3897
+ if (select.nextElementSibling && select.nextElementSibling.classList.contains('select-container-custom')) {
3898
+ // Already initialized, just sync selected value
3899
+ const container = select.nextElementSibling;
3900
+ const triggerSpan = container.querySelector('.select-trigger-custom span');
3901
+ const selectedOpt = select.options[select.selectedIndex];
3902
+ if (selectedOpt && triggerSpan) {
3903
+ triggerSpan.textContent = selectedOpt.textContent;
3904
+ }
3905
+ return;
3906
+ }
3907
+ select.style.display = 'none';
3908
+ const container = document.createElement('div');
3909
+ container.className = 'select-container-custom';
3910
+
3911
+ // Match specific element custom min-widths
3912
+ if (select.id === 'heatmap-months-select') {
3913
+ container.style.minWidth = '110px';
3914
+ } else if (select.id === 'year-select') {
3915
+ container.style.minWidth = '90px';
3916
+ } else if (select.id === 'filter-type') {
3917
+ container.style.minWidth = '130px';
3918
+ }
3919
+
3920
+ const trigger = document.createElement('div');
3921
+ trigger.className = 'select-trigger-custom';
3922
+ const triggerSpan = document.createElement('span');
3923
+ trigger.appendChild(triggerSpan);
3924
+ container.appendChild(trigger);
3925
+ const optionsContainer = document.createElement('div');
3926
+ optionsContainer.className = 'select-options-custom';
3927
+ container.appendChild(optionsContainer);
3928
+
3929
+ function syncSelected() {
3930
+ const selectedOpt = select.options[select.selectedIndex] || select.options[0];
3931
+ if (selectedOpt) {
3932
+ triggerSpan.textContent = selectedOpt.textContent;
3933
+ Array.from(optionsContainer.children).forEach(child => {
3934
+ if (child.getAttribute('data-value') === select.value) {
3935
+ child.classList.add('selected');
3936
+ } else {
3937
+ child.classList.remove('selected');
3938
+ }
3939
+ });
3940
+ }
3941
+ }
3942
+
3943
+ function populateOptions() {
3944
+ optionsContainer.innerHTML = '';
3945
+ Array.from(select.options).forEach(opt => {
3946
+ const optDiv = document.createElement('div');
3947
+ optDiv.className = 'select-option-custom';
3948
+ optDiv.textContent = opt.textContent;
3949
+ optDiv.setAttribute('data-value', opt.value);
3950
+ optDiv.addEventListener('click', (e) => {
3951
+ e.stopPropagation();
3952
+ select.value = opt.value;
3953
+ select.dispatchEvent(new Event('change'));
3954
+ syncSelected();
3955
+ container.classList.remove('open');
3956
+ });
3957
+ optionsContainer.appendChild(optDiv);
3958
+ });
3959
+ }
3960
+
3961
+ populateOptions();
3962
+ syncSelected();
3963
+
3964
+ trigger.addEventListener('click', (e) => {
3965
+ e.stopPropagation();
3966
+ const isOpen = container.classList.contains('open');
3967
+ document.querySelectorAll('.select-container-custom').forEach(el => {
3968
+ el.classList.remove('open');
3969
+ });
3970
+ if (!isOpen) {
3971
+ populateOptions();
3972
+ syncSelected();
3973
+ container.classList.add('open');
3974
+ setTimeout(() => {
3975
+ const selectedEl = optionsContainer.querySelector('.select-option-custom.selected');
3976
+ if (selectedEl) {
3977
+ const itemHeight = selectedEl.offsetHeight || 36;
3978
+ optionsContainer.scrollTop = Math.max(0, selectedEl.offsetTop - itemHeight);
3979
+ }
3980
+ }, 10);
3981
+ }
3982
+ });
3983
+
3984
+ select.parentNode.insertBefore(container, select.nextSibling);
3985
+ select.addEventListener('change', syncSelected);
3986
+
3987
+ // Watch for dynamic options updates
3988
+ const observer = new MutationObserver(() => {
3989
+ syncSelected();
3990
+ });
3991
+ observer.observe(select, { childList: true, subtree: true });
3992
+
3993
+ setTimeout(syncSelected, 200);
3994
+ setTimeout(syncSelected, 1000);
3995
+ });
3996
+
3997
+ // Global click listener to close options dropdowns when clicking outside
3998
+ if (!window.customSelectGlobalBound) {
3999
+ window.customSelectGlobalBound = true;
4000
+ document.addEventListener('click', () => {
4001
+ document.querySelectorAll('.select-container-custom').forEach(el => {
4002
+ el.classList.remove('open');
4003
+ });
4004
+ });
4005
+ }
4006
+ }
4007
+
4008
+
4009
+ fetchInitialData();
4010
+ flatpickr("input[type='date']", {
4011
+ locale: "pt",
4012
+ dateFormat: "Y-m-d",
4013
+ altInput: true,
4014
+ altFormat: "d/m/Y",
4015
+ allowInput: true,
4016
+ disableMobile: true
4017
+ });
4018
+
4019
+ checkLocale();
4020
+
4021
+ // ADR-027 Live-update listener
4022
+ window.onAppDataChanged = function(entities) {
4023
+ var affected = entities.some(function(tag) {
4024
+ return ['creditCard', 'transaction', 'account', 'bill', 'category', 'tag'].indexOf(tag) !== -1;
4025
+ });
4026
+ if (affected) {
4027
+ console.log("cards refetching due to entity change:", entities);
4028
+ fetchInitialData();
4029
+ }
4030
+ };
4031
+
4032
+ </script>