Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
156 commits
Select commit Hold shift + click to select a range
8a9a37b
Precisamos adicionar uma situacao de conversao correta de moedas entr…
otaviio-aug May 16, 2025
147cc3b
Copie o formato da transacao debaixo para a visualiaao das contas. Pr…
otaviio-aug May 16, 2025
70d859a
For Point 2 (Recording Internal Currency Conversions within Wise as a…
otaviio-aug May 16, 2025
0017089
A quantidade em real que esta chegando na conta da nubank ainda nao e…
otaviio-aug May 16, 2025
852af8a
Melhore o nosso app para o mobile, o menu nao esta aparecendo no celular
otaviio-aug May 16, 2025
ff57081
Nas tranferencias ainda nao esta dando certo o rate, na verdade vamos…
otaviio-aug May 16, 2025
ffa239f
Agora, preciso que meio que voce crie uma funcao de exportar os dados…
otaviio-aug May 20, 2025
8819983
Fiz o rollback para depois de adicionar a funcao, vamos tentar novame…
otaviio-aug May 20, 2025
7a9e912
Acho que voce nao percebeu que fiz o rollback. Analise o codigo
otaviio-aug May 20, 2025
9743c0f
I see this error with the app, reported by NextJS, please fix it. The…
otaviio-aug May 20, 2025
ac63dee
Ele esta exportando em multiplos arquivos separados, nao tem como col…
otaviio-aug May 20, 2025
ae49f30
Nao, vai ter que ser em abas, pois precisa ter os cabecalhos para a i…
otaviio-aug May 20, 2025
86b3d73
Mude o nome da aba para Data Management
otaviio-aug May 20, 2025
d99571f
Como faremos para ser um backup num arquivo so? Voce pode meio que ma…
otaviio-aug May 20, 2025
317e4f5
I see this error with the app, reported by NextJS, please fix it. The…
otaviio-aug May 20, 2025
bfe6173
Faca isso para mim
otaviio-aug May 20, 2025
b7499e1
Nao quero ter que colocar os campos manualmente na importacao do arqu…
otaviio-aug May 20, 2025
0de449c
I see this error with the app, reported by NextJS, please fix it. The…
otaviio-aug May 20, 2025
9ed1443
Perfeito, acho que funcionou, so precisamos adicionar as partes que e…
otaviio-aug May 20, 2025
9d4a504
Voce e quase perfeito! hahah mas a importacao de volta para o sistema…
otaviio-aug May 20, 2025
bf46616
Novamente, o primeiro print e de como as contas sao corretamentes (ex…
otaviio-aug May 21, 2025
daf0484
Somente na hora que vou importar um arquivo do proprio App ele aparec…
otaviio-aug May 21, 2025
969d54e
As transacoes vieram corretas mas os calculos finais de cada conta na…
otaviio-aug May 21, 2025
450b681
Perfeito, deu certo, so mais uma alteracao antes do rollout, altere o…
otaviio-aug May 21, 2025
59ccdd2
Vamos melhorar a dashboard um pouco agora, no lugar do card de Top Sp…
otaviio-aug May 21, 2025
df41ec9
Show, so adicione o valor total em algum lugar
otaviio-aug May 21, 2025
7a90891
So assim ficou muito feio kkk, coloque de um jeito diferente e diminu…
otaviio-aug May 21, 2025
05d92be
I see this error with the app, reported by NextJS, please fix it. The…
otaviio-aug May 21, 2025
ecb3d6e
Otimo, agora um ultimo ajuste, eu so consigo acessar as minhas transa…
otaviio-aug May 21, 2025
6116ccc
Voce consegue criar uma landing page de apresentacao do nosso app?
otaviio-aug May 21, 2025
ce1bc2e
Na verdade o nome do app sera GoldQuest e faca ela mais remetendo ao …
otaviio-aug May 21, 2025
da60ce5
I see this error with the app, reported by NextJS, please fix it. The…
otaviio-aug May 21, 2025
73d91a4
I see this error with the app, reported by NextJS, please fix it. The…
otaviio-aug May 21, 2025
40faec1
Ai ficou demais o texto, muito gamificado kkkk. Faca mais sutil ainda…
otaviio-aug May 21, 2025
84fa38d
Ok, pode aplicar
otaviio-aug May 21, 2025
9082c1b
Voce nao aplicou
otaviio-aug May 26, 2025
bf3c605
Make the following changes:
otaviio-aug May 26, 2025
5c28b1a
I see this error with the app, reported by NextJS, please fix it. The…
otaviio-aug May 26, 2025
78bfc48
E retire a explicacao "Sum of all included accounts convertes to €" p…
otaviio-aug May 27, 2025
91eed38
Inclusive o nome do grafico de expenses esta errado, esta como Income…
otaviio-aug May 27, 2025
3cd0e11
E transforme o grafico de Income & expenses em um grafico de barras
otaviio-aug May 27, 2025
f252767
Voce pode conetar a API do yahoo finances ou google finances para atu…
otaviio-aug May 27, 2025
0a50473
Otimo, agora conseguimos permitir que o usuario rastreie sua carteira…
otaviio-aug May 27, 2025
efecedc
Otimo, mas acho que ficara confuso, essa parte do Investimentos, vamo…
otaviio-aug May 27, 2025
d6d6ebd
Perfeito, no lugar dos marlet prices no DeFi coloque apenas cryptos, …
otaviio-aug May 27, 2025
6442cd6
Agora na aba preferences vamos duplicar a funcao de Preferred currenc…
otaviio-aug May 27, 2025
0441a0c
Ta bem, ate agora estamos muito bem mas para comecar a fazer a organi…
otaviio-aug May 27, 2025
3c4f7be
Isso, agora me ajude a pensar na melhor forma de fazer isso, pensando…
otaviio-aug May 27, 2025
d3c88a1
Nao, nao era pra voce colocar isso kkkkk. era pra voce so me ajudar a…
otaviio-aug May 27, 2025
8a9e54a
I see this error with the app, reported by NextJS, please fix it. The…
otaviio-aug May 27, 2025
78a2f02
O valor final nas contas esta errado. Fiz o rollback para antes de me…
otaviio-aug May 27, 2025
aa1b6b5
I see this error with the app, reported by NextJS, please fix it. The…
otaviio-aug May 27, 2025
79a079f
Voce so descreveu e na aplicou
otaviio-aug May 27, 2025
e845045
Corrija para mim
otaviio-aug May 27, 2025
44d960a
Ainda nao fez as alteracoes
otaviio-aug May 27, 2025
dabeca2
corrija para mim
otaviio-aug May 27, 2025
aa60fdb
I see this error with the app, reported by NextJS, please fix it. The…
otaviio-aug May 27, 2025
554e6fc
I see this error with the app, reported by NextJS, please fix it. The…
otaviio-aug May 27, 2025
b2a505b
I see this error with the app, reported by NextJS, please fix it. The…
otaviio-aug May 27, 2025
4520be2
I see this error with the app, reported by NextJS, please fix it. The…
otaviio-aug May 27, 2025
b915345
I see this error with the app, reported by NextJS, please fix it. The…
otaviio-aug May 27, 2025
21e5217
Tentando colocar os Icones dos Bancos e Instituicoes
otaviio-aug May 27, 2025
65d5809
I see this error with the app, reported by NextJS, please fix it. The…
otaviio-aug May 27, 2025
727a9da
I see this error with the app, reported by NextJS, please fix it. The…
otaviio-aug May 27, 2025
54445b3
I see this error with the app, reported by NextJS, please fix it. The…
otaviio-aug May 27, 2025
8b9a4b4
I see this error with the app, reported by NextJS, please fix it. The…
otaviio-aug May 27, 2025
480089b
I see this error with the app, reported by NextJS, please fix it. The…
otaviio-aug May 27, 2025
d68db84
I see this error with the app, reported by NextJS, please fix it. The…
otaviio-aug May 27, 2025
d6035ea
I see this error with the app, reported by NextJS, please fix it. The…
otaviio-aug May 27, 2025
00f1a15
I see this error with the app, reported by NextJS, please fix it. The…
otaviio-aug May 27, 2025
3a32a71
Cada hora esta sendo um nome diferente, nao podemos continuar fazendo…
otaviio-aug May 27, 2025
a882b96
The `npm install` command failed in my project. Analyze the following…
otaviio-aug May 27, 2025
eb0f216
Pronto, instalei tanto o yarn quanto o npm
otaviio-aug May 27, 2025
1a72432
Voltamos ao mesmo erro de antes depois de rodar o yarn e a npm, o que…
otaviio-aug May 27, 2025
6a6a1c1
Okay, agora vamos pensar qual a melhor forma de implantar os icones d…
otaviio-aug May 27, 2025
b8743b9
Mesmo voce alterando nao voltou a exibir o painel mesmo com o icone g…
otaviio-aug May 27, 2025
542d91b
I see this error with the app, reported by NextJS, please fix it. The…
otaviio-aug May 27, 2025
b0ac8fc
Puxe exclusivamente o icone do Nubak
otaviio-aug May 27, 2025
7bb6ca7
I see this error with the app, reported by NextJS, please fix it. The…
otaviio-aug May 27, 2025
8a31fab
I see this error with the app, reported by NextJS, please fix it. The…
otaviio-aug May 27, 2025
026efc4
I see this error with the app, reported by NextJS, please fix it. The…
otaviio-aug May 27, 2025
b7ab1ae
Porque voce colocou os outros novamente? Tinha falado para focarmos e…
otaviio-aug May 27, 2025
36d4f8e
Podemos usar essa biblioteca tambem e ela tem as cores https://simple…
otaviio-aug May 27, 2025
4e8faf7
I see this error with the app, reported by NextJS, please fix it. The…
otaviio-aug May 27, 2025
7878343
Nao deu certo, somente o do Nubank esta certo ainda, pelo que entendi…
otaviio-aug May 27, 2025
358d8a2
Show, a lista que precisamos corrigir e essa popularBanks, voce nao c…
otaviio-aug May 27, 2025
7c61086
I see this error with the app, reported by NextJS, please fix it. The…
otaviio-aug May 27, 2025
8dcc81c
Ótima observação! Esse é um problema comum: o nome do banco no seu ap…
otaviio-aug May 27, 2025
6073c3b
Isso, pode aplicar essas alteracoes
otaviio-aug May 27, 2025
656ac6e
I see this error with the app, reported by NextJS, please fix it. The…
otaviio-aug May 27, 2025
5f3275a
Pode continuar
otaviio-aug May 27, 2025
ee884b6
Nao e para fazer isso, isso e para ser o fallback, apenas se nao cons…
otaviio-aug May 27, 2025
64e3b87
Pode aplicar as mudancas entao e me avise quando estiver pronto para …
otaviio-aug May 27, 2025
0eacc40
voce ainda nao alterou nada, implemente todas as mudancas que voce su…
otaviio-aug May 27, 2025
a78b22b
Aplique o que voce descreveu que ia fazer
otaviio-aug May 27, 2025
a83ef4b
A opcao de pago, nao esta funcionando. Quando clico ela nao faz nada,…
otaviio-aug Jun 2, 2025
746d26f
I see this error with the app, reported by NextJS, please fix it. The…
otaviio-aug Jun 2, 2025
7b13263
ainda nao esta funcionando
otaviio-aug Jun 2, 2025
a28844b
I see this error with the app, reported by NextJS, please fix it. The…
otaviio-aug Jun 2, 2025
e3819a2
Agora ao inves de ficar marcado quando uma foi criada, ela somente cr…
otaviio-aug Jun 2, 2025
e02eb3a
Alguma coisa baguncou meu saldo, e porque quando clico em uma conta n…
otaviio-aug Jun 2, 2025
edd4a10
Ja sei o que houve, quando clique para marcar como pago ela criou mai…
otaviio-aug Jun 2, 2025
6d99be2
Quase perfeito, so faltou lembrar o saldo inicial, por exemplo na min…
otaviio-aug Jun 2, 2025
8acd183
Nao, esta tudo errado agora alguns valores dobraram
otaviio-aug Jun 2, 2025
46cfd9a
I see this error with the app, reported by NextJS, please fix it. The…
otaviio-aug Jun 2, 2025
8cdbf16
Nao esta importando as transacoes. E ainda criou transacoes como Open…
otaviio-aug Jun 2, 2025
718bdbd
I see this error with the app, reported by NextJS, please fix it. The…
otaviio-aug Jun 2, 2025
ea486ad
The NextJS app server is having trouble starting. Please identify wha…
otaviio-aug Jun 3, 2025
6f13d2d
Na hora que vou cadastrar uma transacao, as contas nao estao mudando …
otaviio-aug Jun 3, 2025
3077d8c
Na Aba de Accounts, vamos mudar um pouco o visual, ao inves de lista …
otaviio-aug Jun 3, 2025
97d8d9d
Porque o simbolo do R$ e do $ aparecem na frente do numero e o do € a…
otaviio-aug Jun 3, 2025
286fece
E como faz para ver as subcontas agora?
otaviio-aug Jun 3, 2025
acb44ae
criei um swap mas nada aconteceu na conta, mesmo a conta da wise nao …
otaviio-aug Jun 3, 2025
0cf4008
Vamos melhorar a nossa dashboard tambem, transforme ela igual nesse e…
otaviio-aug Jun 3, 2025
a0a56e6
aplique a correcao
otaviio-aug Jun 3, 2025
705c4b4
I see this error with the app, reported by NextJS, please fix it. The…
otaviio-aug Jun 3, 2025
933eeab
I see this error with the app, reported by NextJS, please fix it. The…
otaviio-aug Jun 3, 2025
95a3657
Ficou show mas esta com muitos espacoes desnecessarios
otaviio-aug Jun 3, 2025
364d87d
Retire esse espaco que desenhei
otaviio-aug Jun 3, 2025
9dd0841
Voce nao fez os ajustes
otaviio-aug Jun 3, 2025
4a105c5
Mas voce nao alterou nada denovo kkk
otaviio-aug Jun 3, 2025
d82b616
Nao foi remodivo ainda mas tudo bem, na verdade crie um card igual a …
otaviio-aug Jun 3, 2025
2e161c9
voce nao alterou nada
otaviio-aug Jun 4, 2025
0ff8b99
O card nao esta expandindo para mostrar as contas mas ja vamos aprove…
otaviio-aug Jun 4, 2025
e53160e
Tem espaco para escrever todo o nome da conta
otaviio-aug Jun 4, 2025
2606925
Ainda tem um espaco muito bom entre os cards, crie um card para visua…
otaviio-aug Jun 4, 2025
e71ecd5
Voce so descreveu a solucao e nao aplicou
otaviio-aug Jun 4, 2025
a63adc5
Make the following changes:
otaviio-aug Jun 4, 2025
7c627d5
I see this error with the app, reported by NextJS, please fix it. The…
otaviio-aug Jun 4, 2025
820b1f8
Na verdade, as subscriptions nao precisa ter um grafico, somente o no…
otaviio-aug Jun 4, 2025
f3e3cda
Inverta os cards de Upcomingo Bills com o card de Statistics de lugar.
otaviio-aug Jun 4, 2025
f6da46a
Show, pode mudar o upcoming Bills de lugar com o Budget Managment
otaviio-aug Jun 4, 2025
bccc24c
Voce nao alterou nada
otaviio-aug Jun 4, 2025
f88060c
Show! fACA O MESMO NO CARD DAS sTATISTICS
otaviio-aug Jun 4, 2025
812793a
Top! aGORA O MESMO COM O RECENT tRANSACTIONS
otaviio-aug Jun 4, 2025
3cddb44
Top, agora mude o nome dele para transactions e o sincronize para apa…
otaviio-aug Jun 4, 2025
c90716e
Ainda nao esta aparecendo todas as transacoes do mes selecionado por …
otaviio-aug Jun 4, 2025
2ed0b43
Nao, so que ao inves de aumentar o tamanho do card para mostrar a lis…
otaviio-aug Jun 4, 2025
c0d3a2e
Make the following changes:
otaviio-aug Jun 4, 2025
7a9f824
Perfeito, agora ajuste o card e o grafico em Statistics para refletir…
otaviio-aug Jun 4, 2025
c2c23e4
Show, porem quando for selecionado por ano ou todo o periodo, ele mos…
otaviio-aug Jun 4, 2025
d9baf22
Porque mudou para spending Statistics? Ao inves disso, crie duas barr…
otaviio-aug Jun 4, 2025
5dc0dee
Porque esta marcando como no dia 25 de cada mes?
otaviio-aug Jun 4, 2025
839eb8f
Aplique a correcao
otaviio-aug Jun 4, 2025
9c6bd21
Ainda esta marcando o 25, nao sei pq
otaviio-aug Jun 4, 2025
e6689a5
Nao, nao foi o que eu queria. Fiz o Rollback, pois vamos alterar de p…
otaviio-aug Jun 4, 2025
46a4fe8
Voce so descreveu e nao alterou
otaviio-aug Jun 4, 2025
c1c3fb0
Pode continuar a alteracao
otaviio-aug Jun 4, 2025
2faa611
Vamos tentar novamente. No formulario de adicionar uma transacao, de …
otaviio-aug Jun 4, 2025
124936c
voce nao fez a correcao
otaviio-aug Jun 4, 2025
81730ee
Voce travou denovo, continue a correcao
otaviio-aug Jun 4, 2025
ce9f962
Ainda nao esta atualizando nos cards, no grafico ate que atualizou, a…
otaviio-aug Jun 4, 2025
e416e2f
No total balance deu certo mas nas contas em si ainda nao
otaviio-aug Jun 4, 2025
7b494c5
Os cards na aba accounts nao atualizaram tambem
otaviio-aug Jun 4, 2025
6fdd24c
fix: corrige cálculo de saldos durante restauração de backup
Jun 11, 2025
1e14863
Fix/CardsImport
Jun 11, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2,920 changes: 1,970 additions & 950 deletions package-lock.json

Large diffs are not rendered by default.

84 changes: 47 additions & 37 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev --turbopack -p 9002",
"dev": "next dev --turbopack",
"genkit:dev": "genkit start -- tsx src/ai/dev.ts",
"genkit:watch": "genkit start -- tsx --watch src/ai/dev.ts",
"build": "next build",
Expand All @@ -13,59 +13,69 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@genkit-ai/googleai": "^1.6.2",
"@genkit-ai/next": "^1.6.2",
"@genkit-ai/googleai": "^1.10.0",
"@genkit-ai/next": "^1.10.0",
"@hookform/resolvers": "^4.1.3",
"@radix-ui/react-accordion": "^1.2.3",
"@radix-ui/react-alert-dialog": "^1.1.6",
"@radix-ui/react-avatar": "^1.1.3",
"@radix-ui/react-checkbox": "^1.1.4",
"@radix-ui/react-dialog": "^1.1.6",
"@radix-ui/react-dropdown-menu": "^2.1.6",
"@radix-ui/react-label": "^2.1.2",
"@radix-ui/react-menubar": "^1.1.6",
"@radix-ui/react-popover": "^1.1.6",
"@radix-ui/react-progress": "^1.1.2",
"@radix-ui/react-radio-group": "^1.2.3",
"@radix-ui/react-scroll-area": "^1.2.3",
"@radix-ui/react-select": "^2.1.6",
"@radix-ui/react-separator": "^1.1.2",
"@radix-ui/react-slider": "^1.2.3",
"@radix-ui/react-slot": "^1.1.2",
"@radix-ui/react-switch": "^1.1.3",
"@radix-ui/react-tabs": "^1.1.3",
"@radix-ui/react-toast": "^1.2.6",
"@radix-ui/react-tooltip": "^1.1.8",
"@tanstack-query-firebase/react": "^1.0.5",
"@tanstack/react-query": "^5.66.0",
"@radix-ui/react-accordion": "^1.2.11",
"@radix-ui/react-alert-dialog": "^1.1.14",
"@radix-ui/react-avatar": "^1.1.10",
"@radix-ui/react-checkbox": "^1.3.2",
"@radix-ui/react-collapsible": "^1.1.11",
"@radix-ui/react-compose-refs": "^1.1.2",
"@radix-ui/react-dialog": "^1.1.14",
"@radix-ui/react-dropdown-menu": "^2.1.15",
"@radix-ui/react-id": "^1.1.1",
"@radix-ui/react-label": "^2.1.7",
"@radix-ui/react-menubar": "^1.1.15",
"@radix-ui/react-popover": "^1.1.14",
"@radix-ui/react-primitive": "^2.1.3",
"@radix-ui/react-progress": "^1.1.7",
"@radix-ui/react-radio-group": "^1.3.7",
"@radix-ui/react-scroll-area": "^1.2.9",
"@radix-ui/react-select": "^2.2.5",
"@radix-ui/react-separator": "^1.1.7",
"@radix-ui/react-slider": "^1.3.5",
"@radix-ui/react-switch": "^1.2.5",
"@radix-ui/react-tabs": "^1.1.12",
"@radix-ui/react-toast": "^1.2.14",
"@radix-ui/react-tooltip": "^1.2.7",
"@radix-ui/react-use-effect-event": "^0.0.2",
"@radix-ui/react-use-escape-keydown": "^1.1.1",
"@radix-ui/react-use-is-hydrated": "^0.1.0",
"@radix-ui/react-use-rect": "^1.1.1",
"@tanstack-query-firebase/react": "^1.0.7",
"@tanstack/react-query": "^5.77.2",
"@token-icons/react": "2.14.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.0.0",
"cmdk": "^1.1.1",
"date-fns": "^3.6.0",
"emoji-picker-react": "^4.10.0",
"firebase": "^11.3.0",
"genkit": "^1.6.2",
"emoji-picker-react": "^4.12.2",
"firebase": "^11.8.1",
"genkit": "^1.10.0",
"jszip": "^3.10.1",
"lucide-react": "^0.475.0",
"next": "15.2.3",
"papaparse": "^5.4.1",
"papaparse": "^5.5.3",
"patch-package": "^8.0.0",
"react": "^18.3.1",
"react-day-picker": "^8.10.1",
"react-dom": "^18.3.1",
"react-hook-form": "^7.54.2",
"recharts": "^2.15.1",
"tailwind-merge": "^3.0.1",
"react-hook-form": "^7.56.4",
"react-icons": "^5.5.0",
"recharts": "^2.15.3",
"tailwind-merge": "^3.3.0",
"tailwindcss-animate": "^1.0.7",
"zod": "^3.24.2"
"zod": "^3.24.1"
},
"devDependencies": {
"@types/node": "^20",
"@types/papaparse": "^5.3.14",
"@types/papaparse": "^5.3.16",
"@types/react": "^18",
"@types/react-dom": "^18",
"genkit-cli": "^1.6.1",
"genkit-cli": "^1.10.0",
"postcss": "^8",
"tailwindcss": "^3.4.1",
"tailwindcss": "^3.4.17",
"typescript": "^5"
}
}
88 changes: 47 additions & 41 deletions src/app/accounts/[accountId]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { getUserPreferences } from '@/lib/preferences';
import { format as formatDateFns, parseISO, isWithinInterval, isSameDay } from 'date-fns';
import { Button } from '@/components/ui/button';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"; // Removed DialogDescription
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from "@/components/ui/alert-dialog";
import { Edit, Trash2, MoreHorizontal, PlusCircle, ArrowDownCircle, ArrowUpCircle, ArrowLeftRight as TransferIcon, ChevronDown, ArrowLeft, CopyPlus } from 'lucide-react';
import AddTransactionForm from '@/components/transactions/add-transaction-form';
Expand All @@ -26,6 +26,7 @@ import MonthlySummarySidebar from '@/components/transactions/monthly-summary-sid
import SpendingChart from '@/components/dashboard/spending-chart';
import { useDateRange } from '@/contexts/DateRangeContext';
import Link from 'next/link';
import { useAuthContext } from '@/contexts/AuthContext';

const formatDate = (dateString: string): string => {
try {
Expand All @@ -42,6 +43,7 @@ export default function AccountDetailPage() {
const params = useParams();
const router = useRouter();
const accountId = typeof params.accountId === 'string' ? params.accountId : undefined;
const { user, isLoadingAuth } = useAuthContext();

const [account, setAccount] = useState<Account | null>(null);
const [transactions, setTransactions] = useState<Transaction[]>([]);
Expand All @@ -61,11 +63,11 @@ export default function AccountDetailPage() {
const [isDeleting, setIsDeleting] = useState(false);
const [clonedTransactionData, setClonedTransactionData] = useState<Partial<AddTransactionFormData> | undefined>(undefined);


const fetchData = useCallback(async () => {
if (!accountId || typeof window === 'undefined') {
if (!user || isLoadingAuth || typeof window === 'undefined' || !accountId) {
setIsLoading(false);
if(!accountId) setError("Account ID is missing.");
if(!accountId && !isLoadingAuth && user) setError("Account ID is missing.");
else if (!user && !isLoadingAuth) setError("Please log in to view account details.");
return;
}
setIsLoading(true);
Expand Down Expand Up @@ -102,37 +104,36 @@ export default function AccountDetailPage() {
} finally {
setIsLoading(false);
}
}, [accountId, toast]);
}, [accountId, toast, user, isLoadingAuth]);

useEffect(() => {
fetchData();
}, [fetchData]);
if (user && !isLoadingAuth) {
fetchData();
} else if (!isLoadingAuth && !user) {
setIsLoading(false);
setAccount(null);
setTransactions([]);
setError("Please log in to view account details.");
}
}, [fetchData, user, isLoadingAuth]);

useEffect(() => {
const handleStorageChange = (event: StorageEvent) => {
if (typeof window !== 'undefined' && event.type === 'storage') {
if (typeof window !== 'undefined' && event.type === 'storage' && user && !isLoadingAuth) {
const isLikelyOurCustomEvent = event.key === null;
const relevantKeysForThisPage = ['userAccounts', 'userPreferences', 'userCategories', 'userTags', `transactions-${accountId}`];
const isRelevantExternalChange = typeof event.key === 'string' && relevantKeysForThisPage.some(k => event.key.includes(k));

const isRelevantExternalChange = typeof event.key === 'string' && relevantKeysForThisPage.some(k => event.key && event.key.includes(k));

if (isLikelyOurCustomEvent || isRelevantExternalChange) {
console.log(`Storage change for account ${accountId} (key: ${event.key || 'custom'}), refetching data...`);
fetchData();
}
}
};

if (typeof window !== 'undefined') {
window.addEventListener('storage', handleStorageChange);
}

if (typeof window !== 'undefined') window.addEventListener('storage', handleStorageChange);
return () => {
if (typeof window !== 'undefined') {
window.removeEventListener('storage', handleStorageChange);
}
if (typeof window !== 'undefined') window.removeEventListener('storage', handleStorageChange);
};
}, [accountId, fetchData]);
}, [accountId, fetchData, user, isLoadingAuth]);


const filteredTransactions = useMemo(() => {
Expand All @@ -146,17 +147,14 @@ export default function AccountDetailPage() {

const spendingData = useMemo(() => {
if (isLoading || !account || !filteredTransactions.length) return [];

const categoryTotals: { [key: string]: number } = {};

filteredTransactions.forEach(tx => {
if (tx.amount < 0 && tx.category !== 'Transfer') {
const convertedAmount = convertCurrency(Math.abs(tx.amount), tx.transactionCurrency, preferredCurrency);
const category = tx.category || 'Uncategorized';
categoryTotals[category] = (categoryTotals[category] || 0) + convertedAmount;
}
});

return Object.entries(categoryTotals)
.map(([category, amount]) => ({ category: category.charAt(0).toUpperCase() + category.slice(1), amount }))
.sort((a, b) => b.amount - a.amount);
Expand Down Expand Up @@ -187,7 +185,6 @@ export default function AccountDetailPage() {
setSelectedTransaction(null);
toast({ title: "Success", description: `Transaction "${transactionToUpdate.description}" updated.` });
window.dispatchEvent(new Event('storage'));
// fetchData(); // Let the storage event handle the refetch
} catch (err: any) {
console.error("Failed to update transaction:", err);
toast({ title: "Error", description: err.message || "Could not update transaction.", variant: "destructive" });
Expand All @@ -207,7 +204,6 @@ export default function AccountDetailPage() {
await deleteTransaction(selectedTransaction.id, selectedTransaction.accountId);
toast({ title: "Transaction Deleted", description: `Transaction "${selectedTransaction.description}" removed.` });
window.dispatchEvent(new Event('storage'));
// fetchData(); // Let the storage event handle the refetch
} catch (err: any) {
console.error("Failed to delete transaction:", err);
toast({ title: "Error", description: err.message || "Could not delete transaction.", variant: "destructive" });
Expand All @@ -224,25 +220,24 @@ export default function AccountDetailPage() {
setIsAddTransactionDialogOpen(false);
setClonedTransactionData(undefined);
window.dispatchEvent(new Event('storage'));
// fetchData(); // Let the storage event handle the refetch
} catch (error: any) {
console.error("Failed to add transaction:", error);
toast({ title: "Error", description: `Could not add transaction: ${error.message}`, variant: "destructive" });
}
};

const handleTransferAdded = async (data: { fromAccountId: string; toAccountId: string; amount: number; date: Date; description?: string; tags?: string[]; transactionCurrency: string; }) => {
const handleTransferAdded = async (data: { fromAccountId: string; toAccountId: string; amount: number; date: Date; description?: string; tags?: string[]; transactionCurrency: string; toAccountAmount: number; toAccountCurrency: string;}) => {
try {
const transferAmount = Math.abs(data.amount);
const formattedDate = formatDateFns(data.date, 'yyyy-MM-dd');

const currentAccounts = await getAccounts();
const fromAccountName = currentAccounts.find(a=>a.id === data.fromAccountId)?.name || 'Unknown';
const toAccountName = currentAccounts.find(a=>a.id === data.toAccountId)?.name || 'Unknown';
const desc = data.description || `Transfer from ${fromAccountName} to ${toAccountName}`;

await addTransaction({
accountId: data.fromAccountId,
amount: -transferAmount,
amount: -Math.abs(data.amount),
transactionCurrency: data.transactionCurrency,
date: formattedDate,
description: desc,
Expand All @@ -252,8 +247,8 @@ export default function AccountDetailPage() {

await addTransaction({
accountId: data.toAccountId,
amount: transferAmount,
transactionCurrency: data.transactionCurrency,
amount: Math.abs(data.toAccountAmount),
transactionCurrency: data.toAccountCurrency,
date: formattedDate,
description: desc,
category: 'Transfer',
Expand All @@ -264,7 +259,6 @@ export default function AccountDetailPage() {
setIsAddTransactionDialogOpen(false);
setClonedTransactionData(undefined);
window.dispatchEvent(new Event('storage'));
// fetchData(); // Let the storage event handle the refetch
} catch (error: any) {
console.error("Failed to add transfer:", error);
toast({ title: "Error", description: `Could not record transfer: ${error.message}`, variant: "destructive" });
Expand Down Expand Up @@ -332,7 +326,7 @@ export default function AccountDetailPage() {
return 'All Time';
}, [selectedDateRange]);

if (isLoading && !account) {
if (isLoadingAuth || (isLoading && !account)) {
return (
<div className="container mx-auto py-8 px-4 md:px-6 lg:px-8">
<Skeleton className="h-8 w-1/2 mb-6" />
Expand Down Expand Up @@ -373,6 +367,10 @@ export default function AccountDetailPage() {
);
}

const primaryBalanceEntry = account.balances.find(b => b.currency === account.primaryCurrency) || account.balances[0];
// const displayBalance = primaryBalanceEntry ? primaryBalanceEntry.amount : 0;
// const displayCurrency = primaryBalanceEntry ? primaryBalanceEntry.currency : (account.primaryCurrency || 'N/A');

return (
<div className="container mx-auto py-8 px-4 md:px-6 lg:px-8">
<div className="flex justify-between items-center mb-6">
Expand All @@ -381,9 +379,15 @@ export default function AccountDetailPage() {
<ArrowLeft className="mr-2 h-4 w-4" /> Back to Accounts
</Button>
<h1 className="text-3xl font-bold">{account.name} - Transactions</h1>
<p className="text-muted-foreground">Balance: {formatCurrency(account.balance, account.currency, account.currency, false)}
{account.currency !== preferredCurrency && ` (≈ ${formatCurrency(account.balance, account.currency, preferredCurrency, true)})`}
</p>
<div className="text-muted-foreground mt-1">
{account.balances.map((balance, index) => (
<div key={index} className={balance.currency === account.primaryCurrency ? 'font-semibold text-foreground' : ''}>
{formatCurrency(balance.amount, balance.currency, balance.currency, false)}
{balance.currency.toUpperCase() !== preferredCurrency.toUpperCase() &&
` (≈ ${formatCurrency(balance.amount, balance.currency, preferredCurrency, true)})`}
</div>
))}
</div>
</div>
<DropdownMenu>
<DropdownMenuTrigger asChild>
Expand Down Expand Up @@ -573,6 +577,7 @@ export default function AccountDetailPage() {
categories={allCategories}
tags={allTags}
onTransactionAdded={handleUpdateTransaction}
onTransferAdded={handleTransferAdded}
isLoading={isLoading}
initialData={{
...selectedTransaction,
Expand Down Expand Up @@ -611,11 +616,11 @@ export default function AccountDetailPage() {
initialType={transactionTypeToAdd}
initialData={
clonedTransactionData ||
(transactionTypeToAdd !== 'transfer' && account
? { accountId: account.id, transactionCurrency: account.currency, date: new Date() }
: (transactionTypeToAdd === 'transfer' && account
? { fromAccountId: account.id, transactionCurrency: account.currency, date: new Date() }
: {date: new Date()})
(transactionTypeToAdd !== 'transfer' && account && account.primaryCurrency
? { accountId: account.id, transactionCurrency: account.primaryCurrency, date: new Date() }
: (transactionTypeToAdd === 'transfer' && account && account.primaryCurrency
? { fromAccountId: account.id, transactionCurrency: account.primaryCurrency, date: new Date(), toAccountCurrency: allAccounts.find(a => a.id !== account.id)?.primaryCurrency || account.primaryCurrency }
: {date: new Date()})
)
}
/>
Expand All @@ -626,3 +631,4 @@ export default function AccountDetailPage() {
);
}


Loading