mirror of
https://github.com/felipegcoutinho/openmonetis.git
synced 2026-09-09 13:56:01 +00:00
Compare commits
11 Commits
be6fa6dcfc
...
v2.7.13
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bf4138db82 | ||
|
|
ed9196797b | ||
|
|
532186fe39 | ||
|
|
a2ce7f1283 | ||
|
|
f3c3d98aeb | ||
|
|
24709ec232 | ||
|
|
2fd94118f2 | ||
|
|
01f161f011 | ||
|
|
4741087feb | ||
|
|
32b190ab4e | ||
|
|
d06bac5624 |
8
.github/workflows/ci.yml
vendored
8
.github/workflows/ci.yml
vendored
@@ -33,6 +33,14 @@ jobs:
|
|||||||
node-version: 22
|
node-version: 22
|
||||||
cache: pnpm
|
cache: pnpm
|
||||||
|
|
||||||
|
- name: Cache Next.js build
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: ${{ github.workspace }}/.next/cache
|
||||||
|
key: ${{ runner.os }}-nextjs-${{ hashFiles('pnpm-lock.yaml') }}-${{ hashFiles('src/**/*.ts', 'src/**/*.tsx', 'src/**/*.css', 'next.config.ts') }}
|
||||||
|
restore-keys: |
|
||||||
|
${{ runner.os }}-nextjs-${{ hashFiles('pnpm-lock.yaml') }}-
|
||||||
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: pnpm install --frozen-lockfile
|
run: pnpm install --frozen-lockfile
|
||||||
|
|
||||||
|
|||||||
12
AGENTS.md
12
AGENTS.md
@@ -16,7 +16,7 @@
|
|||||||
3. **Periods** usam formato `YYYY-MM` (ex: `"2025-11"`). Utils em `src/shared/utils/period/`.
|
3. **Periods** usam formato `YYYY-MM` (ex: `"2025-11"`). Utils em `src/shared/utils/period/`.
|
||||||
4. **Moeda**: R$ com 2 decimais. DB: `numeric(12, 2)`. Utils em `src/shared/utils/currency.ts`.
|
4. **Moeda**: R$ com 2 decimais. DB: `numeric(12, 2)`. Utils em `src/shared/utils/currency.ts`.
|
||||||
5. **Revalidation**: usar `revalidateForEntity("entity")` de `src/shared/lib/actions/helpers.ts` apos mutations.
|
5. **Revalidation**: usar `revalidateForEntity("entity")` de `src/shared/lib/actions/helpers.ts` apos mutations.
|
||||||
6. **Versionamento e publicação**: registrar mudancas no `CHANGELOG.md` seguindo Keep a Changelog, também alterar o `package.json` e o badge de versão do `README.md`. Cada versão deve ter um parágrafo introdutório em linguagem humana logo abaixo do cabeçalho `## [x.y.z]`, antes das seções `### Adicionado/Alterado/Removido` — descrevendo em prosa o que a versão representa (ex: "Esta versão foca em polimento visual e reorganização interna..."). A `main` executa somente a CI; imagens Docker e GitHub Releases são publicadas exclusivamente por tags SemVer no formato `vX.Y.Z`. Antes de criar a tag, confirmar que a CI da `main` passou e que tag, `package.json`, `CHANGELOG.md` e badge do `README.md` usam a mesma versão. A tag deve apontar para o commit validado. Criar ou enviar uma tag dispara publicação externa (`X.Y.Z`, `X.Y`, `X` e `latest` no Docker Hub, seguida da GitHub Release), portanto agentes nunca devem criar ou fazer push de tags sem autorização explícita do usuário. Não voltar a publicar `latest` diretamente de pushes na `main`.
|
6. **Versionamento e publicação**: registrar mudancas no `CHANGELOG.md` seguindo Keep a Changelog, também alterar o `package.json` e o badge de versão do `README.md`. Cada versão deve ter um parágrafo introdutório em linguagem humana logo abaixo do cabeçalho `## [x.y.z]`, antes das seções `### Adicionado/Alterado/Removido` — descrevendo em prosa o que a versão representa (ex: "Esta versão foca em polimento visual e reorganização interna..."). A `main` executa somente a CI; imagens Docker e GitHub Releases são publicadas exclusivamente por tags SemVer no formato `vX.Y.Z`. Antes de criar a tag, confirmar que a CI da `main` passou e que tag, `package.json`, `CHANGELOG.md` e badge do `README.md` usam a mesma versão. A tag deve apontar para o commit validado. Criar ou enviar uma tag dispara publicação externa (`X.Y.Z`, `X.Y`, `X` e `latest` no Docker Hub, seguida da GitHub Release), portanto agentes nunca devem criar ou fazer push de tags sem autorização explícita do usuário. Quando o usuário pedir **"commit e push"** em uma mudança que prepara uma nova versão, isso conta como autorização explícita para executar o fluxo completo: commitar, enviar a `main`, aguardar a CI da `main` passar, criar a tag SemVer correspondente à versão preparada e enviar essa tag. Se não houver versão preparada ou se houver divergência entre `package.json`, `CHANGELOG.md`, badge do `README.md` e tag pretendida, parar e pedir confirmação. Não voltar a publicar `latest` diretamente de pushes na `main`.
|
||||||
7. **Comunicacao**: responder em portugues clara e direta com o time.
|
7. **Comunicacao**: responder em portugues clara e direta com o time.
|
||||||
8. **Commit messages**: agrupar por natureza. em pt-br. seguindo o padrao do sistema.
|
8. **Commit messages**: agrupar por natureza. em pt-br. seguindo o padrao do sistema.
|
||||||
9. **README.md**: sempre que fizer alteracoes significativas, atualize o README.md.
|
9. **README.md**: sempre que fizer alteracoes significativas, atualize o README.md.
|
||||||
@@ -364,3 +364,13 @@ Erros nao devem expor stack traces, paths ou nomes de bibliotecas ao cliente. Us
|
|||||||
Verificar pacotes novos sugeridos pela IA em npmjs.com antes de instalar. Red flags: menos de 1.000 downloads/semana, publicado nos ultimos 30 dias, nome muito parecido com pacote popular. Rodar `pnpm audit` periodicamente.
|
Verificar pacotes novos sugeridos pela IA em npmjs.com antes de instalar. Red flags: menos de 1.000 downloads/semana, publicado nos ultimos 30 dias, nome muito parecido com pacote popular. Rodar `pnpm audit` periodicamente.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
<!-- BEGIN:nextjs-agent-rules -->
|
||||||
|
|
||||||
|
# This is NOT the Next.js you know
|
||||||
|
|
||||||
|
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.
|
||||||
|
|
||||||
|
This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.
|
||||||
|
|
||||||
|
<!-- END:nextjs-agent-rules -->
|
||||||
|
|||||||
57
CHANGELOG.md
57
CHANGELOG.md
@@ -5,6 +5,63 @@ Todas as mudanças notáveis deste projeto serão documentadas neste arquivo.
|
|||||||
O formato é baseado em [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/),
|
O formato é baseado em [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/),
|
||||||
e este projeto adere ao [Versionamento Semântico](https://semver.org/lang/pt-BR/).
|
e este projeto adere ao [Versionamento Semântico](https://semver.org/lang/pt-BR/).
|
||||||
|
|
||||||
|
## [2.7.13] - 2026-08-09
|
||||||
|
|
||||||
|
Esta versão atualiza a base técnica do OpenMonetis com as correções de segurança e desempenho do Next.js 16.3, acelera as verificações de tipos, melhora a recuperação de falhas nas áreas mais complexas do aplicativo e corrige a importação de extratos OFX que reutilizam identificadores bancários.
|
||||||
|
|
||||||
|
### Adicionado
|
||||||
|
- Interface: dashboard, Insights, anexos e relatórios agora possuem limites de erro próprios, preservando a navegação e oferecendo uma nova tentativa sem derrubar toda a área autenticada.
|
||||||
|
- Desenvolvimento: agentes de código passam a consultar a documentação do Next.js correspondente à versão instalada no projeto.
|
||||||
|
|
||||||
|
### Alterado
|
||||||
|
- ATENÇÃO — mudança no banco de dados: esta versão adiciona a coluna ofx_import_fingerprint e substitui o índice único baseado apenas no FITID por um índice de fingerprint. Aplique a migração 0034_superb_blonde_phantom.sql antes de iniciar a aplicação atualizada (pnpm run db:migrate em instalações manuais). A imagem Docker tenta aplicar as migrações automaticamente durante a inicialização.
|
||||||
|
- Banco de dados: a deduplicação de importações OFX agora considera os dados completos e a ocorrência de cada transação, em vez de depender somente do FITID fornecido pela instituição financeira.
|
||||||
|
- Dependências: Next.js atualizado para 16.3.0 e TypeScript para 7.0.2.
|
||||||
|
- Desenvolvimento: Turbopack e seus caches passam a usar os padrões nativos do Next.js 16.3, removendo flags redundantes da configuração.
|
||||||
|
- CI: o cache de build em `.next/cache` agora é preservado entre execuções para acelerar compilações sucessivas.
|
||||||
|
|
||||||
|
### Corrigido
|
||||||
|
- Importação: transações OFX legítimas que compartilham o mesmo FITID agora permanecem independentes na revisão e podem ser importadas sem sobrescrever linhas, travar seletores ou serem descartadas como duplicatas (issue #88 - @cunhanai).
|
||||||
|
- Interface: a identidade estável de cada linha evita duplicações visuais e mantém funcionando a seleção, a escolha de categoria e a rolagem da tabela de revisão.
|
||||||
|
- Segurança: incorporadas as correções do Next.js 16.3 para Server Actions, Proxy, cache de respostas e otimização de imagens.
|
||||||
|
- Segurança: o otimizador de imagens agora aceita somente avatares do Google e logos do Logo.dev, removendo os curingas globais de HTTP e HTTPS; anexos do S3 continuam servidos diretamente, sem passar pelo otimizador.
|
||||||
|
|
||||||
|
## [2.7.12] - 2026-06-30
|
||||||
|
|
||||||
|
Esta versão corrige a seleção de faturas e períodos em popovers usados dentro de diálogos, alinhando esses componentes ao mesmo comportamento seguro aplicado recentemente aos seletores de data.
|
||||||
|
|
||||||
|
### Corrigido
|
||||||
|
- Lançamentos: o seletor inline de fatura volta a aceitar cliques no mês em diálogos de criação/edição e no modal de múltiplos lançamentos.
|
||||||
|
- Períodos: botões internos do seletor mensal agora são explicitamente `type="button"`, evitando submits acidentais quando o componente aparece dentro de formulários.
|
||||||
|
- Interface: popovers de período e escolha de logo de estabelecimento passam a usar modo modal quando podem aparecer sobre diálogos, preservando foco e clique.
|
||||||
|
|
||||||
|
## [2.7.11] - 2026-06-28
|
||||||
|
|
||||||
|
Esta atualização melhora a leitura diária dos lançamentos e deixa a nova visualização opcional, mantendo a possibilidade de voltar ao formato anterior quando a lista agrupada não for a melhor escolha para o usuário.
|
||||||
|
|
||||||
|
### Adicionado
|
||||||
|
- Preferências: nova opção `Agrupar por data` em Ajustes > Preferências > Lançamentos para alternar entre a lista agrupada por data e a visualização anterior.
|
||||||
|
- Lançamentos: a lista agora pode exibir uma barra de data por grupo no formato `TER, 26 JUN 2026`, reunindo os lançamentos daquele dia.
|
||||||
|
|
||||||
|
### Alterado
|
||||||
|
- Lançamentos: quando o agrupamento por data está ativo, os cards e linhas deixam de repetir a data em cada item, reduzindo ruído visual e mantendo vencimentos de boleto como informação do lançamento.
|
||||||
|
- Lançamentos: a preferência de agrupamento por data é aplicada nas listagens principais, extratos de conta, faturas de cartão, detalhes de pessoa e detalhes de categoria.
|
||||||
|
- Interface: checkboxes passam a usar um visual mais compacto.
|
||||||
|
- Documentação: o README agora cita o agrupamento por data entre as opções de personalização.
|
||||||
|
|
||||||
|
### Corrigido
|
||||||
|
- Lançamentos: o seletor de data em modais de criação e edição volta a aceitar a data selecionada no calendário.
|
||||||
|
|
||||||
|
## [2.7.10] - 2026-06-27
|
||||||
|
|
||||||
|
Esta versão ajusta a experiência de leitura dos lançamentos parcelados após antecipações, permitindo esconder parcelas já liquidadas por antecipação sem perder o histórico quando ele ainda for necessário.
|
||||||
|
|
||||||
|
### Adicionado
|
||||||
|
- Ajustes: nova preferência `Ocultar parcelas antecipadas` para remover da tabela lançamentos marcados como parcela antecipada.
|
||||||
|
|
||||||
|
### Alterado
|
||||||
|
- Lançamentos: a preferência passa a ser aplicada nas listagens principais, extratos de conta, faturas de cartão, detalhes de pessoa, detalhes de categoria e exportação de lançamentos, preservando paginação e contagens visíveis.
|
||||||
|
|
||||||
## [2.7.9] - 2026-06-21
|
## [2.7.9] - 2026-06-21
|
||||||
|
|
||||||
Esta versão torna a publicação mais previsível ao separar a validação contínua da entrega de versões oficiais. Pull requests e a branch principal continuam sendo verificadas, enquanto imagens Docker e releases passam a ser produzidas somente a partir de uma tag SemVer validada.
|
Esta versão torna a publicação mais previsível ao separar a validação contínua da entrega de versões oficiais. Pull requests e a branch principal continuam sendo verificadas, enquanto imagens Docker e releases passam a ser produzidas somente a partir de uma tag SemVer validada.
|
||||||
|
|||||||
366
CLAUDE.md
366
CLAUDE.md
@@ -1,366 +0,0 @@
|
|||||||
# CLAUDE.md - OpenMonetis
|
|
||||||
|
|
||||||
> Self-hosted personal finance app (Next.js 16, React 19, PostgreSQL, Drizzle ORM, Better Auth, Tailwind 4, shadcn/ui).
|
|
||||||
> Portuguese UI, English folders/imports. Linter: Biome 2.x. Package manager: pnpm.
|
|
||||||
|
|
||||||
## Related Projects
|
|
||||||
|
|
||||||
- **OpenMonetis Companion** (`~/github/openmonetis-companion`): Android app que captura notificacoes de apps bancarios e envia para o OpenMonetis via API. Os itens chegam na feature `inbox` para revisao.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Critical Rules
|
|
||||||
|
|
||||||
1. **Sempre filtrar por `userId`** em queries.
|
|
||||||
2. **Usar `getAdminPayerId(userId)`** de `src/shared/lib/payers/get-admin-id.ts` ao inves de JOIN com `payers` para descobrir o admin.
|
|
||||||
3. **Periods** usam formato `YYYY-MM` (ex: `"2025-11"`). Utils em `src/shared/utils/period/`.
|
|
||||||
4. **Moeda**: R$ com 2 decimais. DB: `numeric(12, 2)`. Utils em `src/shared/utils/currency.ts`.
|
|
||||||
5. **Revalidation**: usar `revalidateForEntity("entity")` de `src/shared/lib/actions/helpers.ts` apos mutations.
|
|
||||||
6. **Versionamento**: registrar mudancas no `CHANGELOG.md` seguindo Keep a Changelog, também altere o `package.json` e `readme.md` (Badges do README.md). Cada versão deve ter um parágrafo introdutório em linguagem humana logo abaixo do cabeçalho `## [x.y.z]`, antes das seções `### Adicionado/Alterado/Removido` — descrevendo em prosa o que a versão representa (ex: "Esta versão foca em polimento visual e reorganização interna...").
|
|
||||||
7. **Comunicacao**: responder em portugues clara e direta com o time.
|
|
||||||
8. **Commit messages**: agrupar por natureza. em pt-br. seguindo o padrao do sistema.
|
|
||||||
9. **README.md**: sempre que fizer alteracoes significativas, atualize o README.md.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Architecture
|
|
||||||
|
|
||||||
### Feature-First
|
|
||||||
|
|
||||||
- `src/app/`: roteamento, layouts, loading states e paginas finas
|
|
||||||
- `src/features/`: codigo de dominio por feature
|
|
||||||
- `src/shared/`: tudo que e genuinamente reutilizado entre features
|
|
||||||
- `src/db/`: schema do banco
|
|
||||||
|
|
||||||
### Regra Feature vs Shared
|
|
||||||
|
|
||||||
Use esta pergunta:
|
|
||||||
|
|
||||||
> Se eu deletar esta feature, este arquivo deveria sumir junto?
|
|
||||||
|
|
||||||
- Sim: vai para `src/features/<feature>/`
|
|
||||||
- Nao: vai para `src/shared/`
|
|
||||||
|
|
||||||
### Features nao importam outras features
|
|
||||||
|
|
||||||
Se um contrato cruza dominios, ele deve morar em `src/shared/`.
|
|
||||||
|
|
||||||
**Excecao intencional: `attachments` depende de `transactions`**
|
|
||||||
|
|
||||||
`src/features/attachments` importa `TransactionDialog`, `TransactionDetailsDialog` e `TransactionItem` diretamente de `src/features/transactions`. Isso e uma dependencia explicita e aceita: anexos sao semanticamente uma extensao de lancamentos — existem por causa deles e nao fazem sentido sem esse contexto. Mover esses componentes para `shared/` seria errado (eles pertencem a transactions). Nao tratar isso como bug a corrigir.
|
|
||||||
|
|
||||||
Exemplos comuns:
|
|
||||||
|
|
||||||
- auth: `src/shared/lib/auth/*`
|
|
||||||
- db: `src/shared/lib/db.ts`
|
|
||||||
- revalidation helpers: `src/shared/lib/actions/*`
|
|
||||||
- payers cross-domain helpers: `src/shared/lib/payers/*`
|
|
||||||
- period/currency/date: `src/shared/utils/*`
|
|
||||||
- shadcn/ui: `src/shared/components/ui/*`
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Directory Structure
|
|
||||||
|
|
||||||
```text
|
|
||||||
src/
|
|
||||||
├── app/
|
|
||||||
│ ├── (auth)/
|
|
||||||
│ │ ├── login/page.tsx
|
|
||||||
│ │ └── signup/page.tsx
|
|
||||||
│ ├── (dashboard)/
|
|
||||||
│ │ ├── dashboard/
|
|
||||||
│ │ ├── transactions/
|
|
||||||
│ │ ├── cards/
|
|
||||||
│ │ │ └── [cardId]/invoice/
|
|
||||||
│ │ ├── accounts/
|
|
||||||
│ │ │ └── [accountId]/statement/
|
|
||||||
│ │ ├── categories/
|
|
||||||
│ │ │ ├── [categoryId]/
|
|
||||||
│ │ │ └── history/
|
|
||||||
│ │ ├── budgets/
|
|
||||||
│ │ ├── payers/
|
|
||||||
│ │ │ └── [payerId]/
|
|
||||||
│ │ ├── notes/
|
|
||||||
│ │ ├── insights/
|
|
||||||
│ │ ├── calendar/
|
|
||||||
│ │ ├── inbox/
|
|
||||||
│ │ ├── attachments/
|
|
||||||
│ │ ├── changelog/
|
|
||||||
│ │ ├── reports/
|
|
||||||
│ │ │ ├── category-trends/
|
|
||||||
│ │ │ ├── card-usage/
|
|
||||||
│ │ │ ├── installment-analysis/
|
|
||||||
│ │ │ └── establishments/
|
|
||||||
│ │ └── settings/
|
|
||||||
│ ├── (landing-page)/
|
|
||||||
│ ├── api/
|
|
||||||
│ ├── globals.css
|
|
||||||
│ └── layout.tsx
|
|
||||||
├── features/ # cada feature segue: actions.ts, queries.ts, actions/, components/, hooks/, lib/
|
|
||||||
│ ├── auth/
|
|
||||||
│ ├── landing/
|
|
||||||
│ ├── dashboard/
|
|
||||||
│ ├── transactions/
|
|
||||||
│ ├── cards/
|
|
||||||
│ ├── invoices/
|
|
||||||
│ ├── accounts/
|
|
||||||
│ ├── categories/
|
|
||||||
│ ├── budgets/
|
|
||||||
│ ├── payers/
|
|
||||||
│ ├── notes/
|
|
||||||
│ ├── insights/
|
|
||||||
│ ├── calendar/
|
|
||||||
│ ├── inbox/
|
|
||||||
│ ├── attachments/
|
|
||||||
│ ├── reports/
|
|
||||||
│ └── settings/
|
|
||||||
├── shared/
|
|
||||||
│ ├── components/
|
|
||||||
│ │ ├── ui/ # shadcn/ui primitives
|
|
||||||
│ │ ├── navigation/ # navbar, sidebar, breadcrumbs
|
|
||||||
│ │ ├── providers/ # React context providers
|
|
||||||
│ │ ├── brand/ # logos do app (logo, logo-icon, logo-text)
|
|
||||||
│ │ ├── widgets/ # widget-card, widget-empty-state, expandable-widget-card
|
|
||||||
│ │ ├── feedback/ # empty-state, status-dot, payment-success
|
|
||||||
│ │ ├── month-picker/
|
|
||||||
│ │ ├── logo-picker/
|
|
||||||
│ │ ├── calculator/
|
|
||||||
│ │ ├── entity-avatar/
|
|
||||||
│ │ └── skeletons/
|
|
||||||
│ ├── hooks/
|
|
||||||
│ ├── lib/
|
|
||||||
│ │ ├── actions/
|
|
||||||
│ │ ├── auth/
|
|
||||||
│ │ ├── accounts/
|
|
||||||
│ │ ├── cards/
|
|
||||||
│ │ ├── calculator/
|
|
||||||
│ │ ├── categories/
|
|
||||||
│ │ ├── email/
|
|
||||||
│ │ ├── import/
|
|
||||||
│ │ ├── installments/
|
|
||||||
│ │ ├── invoices/
|
|
||||||
│ │ ├── logo/
|
|
||||||
│ │ ├── notifications/
|
|
||||||
│ │ ├── payers/
|
|
||||||
│ │ ├── schemas/
|
|
||||||
│ │ ├── storage/
|
|
||||||
│ │ ├── transfers/
|
|
||||||
│ │ ├── types/
|
|
||||||
│ │ ├── version/
|
|
||||||
│ │ └── db.ts
|
|
||||||
│ └── utils/
|
|
||||||
│ ├── period/
|
|
||||||
│ ├── calculator.ts
|
|
||||||
│ ├── calendar.ts
|
|
||||||
│ ├── category-colors.ts
|
|
||||||
│ ├── currency.ts
|
|
||||||
│ ├── date.ts
|
|
||||||
│ ├── export-branding.ts
|
|
||||||
│ ├── fetch-json.ts
|
|
||||||
│ ├── financial-dates.ts
|
|
||||||
│ ├── icons.tsx
|
|
||||||
│ ├── id.ts
|
|
||||||
│ ├── initials.ts
|
|
||||||
│ ├── math.ts
|
|
||||||
│ ├── number.ts
|
|
||||||
│ ├── percentage.ts
|
|
||||||
│ ├── string.ts
|
|
||||||
│ └── ui.ts
|
|
||||||
└── db/
|
|
||||||
└── schema.ts
|
|
||||||
```
|
|
||||||
|
|
||||||
### Estrutura interna padrão de uma feature
|
|
||||||
|
|
||||||
Toda feature em `src/features/<nome>/` segue:
|
|
||||||
|
|
||||||
```text
|
|
||||||
<feature>/
|
|
||||||
├── actions.ts # entry point de Server Actions (barrel quando há actions/)
|
|
||||||
├── queries.ts # entry point de leitura do banco
|
|
||||||
├── actions/ # (opcional) Server Actions divididas por domínio quando o volume cresce
|
|
||||||
├── components/ # componentes de UI da feature
|
|
||||||
├── hooks/ # React hooks específicos da feature
|
|
||||||
└── lib/ # helpers, types, sub-queries e constantes internas
|
|
||||||
```
|
|
||||||
|
|
||||||
`actions.ts` e `queries.ts` são as portas de entrada da feature. Tudo que é helper interno fica em `lib/`. Componentes e hooks ficam nas pastas com nome óbvio.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Import Patterns
|
|
||||||
|
|
||||||
### Preferidos
|
|
||||||
|
|
||||||
```ts
|
|
||||||
import { getUser } from "@/shared/lib/auth/server";
|
|
||||||
import { revalidateForEntity } from "@/shared/lib/actions/helpers";
|
|
||||||
import { parsePeriodParam } from "@/shared/utils/period";
|
|
||||||
import { TransactionsPage } from "@/features/transactions/components/page/transactions-page";
|
|
||||||
import { fetchLancamentos } from "@/features/transactions/queries";
|
|
||||||
```
|
|
||||||
|
|
||||||
### Evitar
|
|
||||||
|
|
||||||
```ts
|
|
||||||
import { Something } from "@/components/...";
|
|
||||||
import { Something } from "@/lib/...";
|
|
||||||
import { something } from "@/app/(dashboard)/...";
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## App Router Pattern
|
|
||||||
|
|
||||||
Paginas em `src/app/` devem ser finas:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
import { getUser } from "@/shared/lib/auth/server";
|
|
||||||
import { TransactionsPage } from "@/features/transactions/components/page/transactions-page";
|
|
||||||
import { fetchLancamentos } from "@/features/transactions/queries";
|
|
||||||
|
|
||||||
export default async function Page() {
|
|
||||||
const user = await getUser();
|
|
||||||
const data = await fetchLancamentos([/* filters */]);
|
|
||||||
return <TransactionsPage {...data} />;
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Layouts, `loading.tsx` e metadata continuam em `src/app/`.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Naming
|
|
||||||
|
|
||||||
### Routes / folders
|
|
||||||
|
|
||||||
| Portugues | English |
|
|
||||||
|---|---|
|
|
||||||
| `lancamentos` | `transactions` |
|
|
||||||
| `cartoes` | `cards` |
|
|
||||||
| `contas` | `accounts` |
|
|
||||||
| `categorias` | `categories` |
|
|
||||||
| `orcamentos` | `budgets` |
|
|
||||||
| `pessoas` | `payers` |
|
|
||||||
|
|
||||||
> **Nota:** o conceito de "pagador" foi renomeado para **"pessoa"** na UI (labels, toasts, textos visíveis ao usuário). O código, rotas e schema continuam usando o termo original em inglês (`payer`, `payerId`, `adminPayerId`) e em português interno (`pagador` como variável). Não renomear esses identificadores — a divergência entre UI e código é intencional e documentada.
|
|
||||||
| `anotacoes` | `notes` |
|
|
||||||
| `calendario` | `calendar` |
|
|
||||||
| `ajustes` | `settings` |
|
|
||||||
| `pre-lancamentos` | `inbox` |
|
|
||||||
| `relatorios/tendencias` | `reports/category-trends` |
|
|
||||||
| `relatorios/uso-cartoes` | `reports/card-usage` |
|
|
||||||
| `relatorios/analise-parcelas` | `reports/installment-analysis` |
|
|
||||||
| `relatorios/estabelecimentos` | `reports/establishments` |
|
|
||||||
| `contas/[contaId]/extrato` | `accounts/[accountId]/statement` |
|
|
||||||
| `cartoes/[cartaoId]/fatura` | `cards/[cardId]/invoice` |
|
|
||||||
| `categorias/historico` | `categories/history` |
|
|
||||||
| `changelog` | `settings/changelog` |
|
|
||||||
|
|
||||||
### Files
|
|
||||||
|
|
||||||
- preferir `kebab-case`
|
|
||||||
- preferir nomes em ingles
|
|
||||||
- manter nomes internos de tipos/funcoes somente quando a troca aumentar risco sem ganho real
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Commands
|
|
||||||
|
|
||||||
```bash
|
|
||||||
pnpm run dev
|
|
||||||
pnpm run build
|
|
||||||
pnpm run lint
|
|
||||||
pnpm run lint:fix
|
|
||||||
pnpm exec next typegen
|
|
||||||
pnpm exec tsc --noEmit
|
|
||||||
pnpm run db:generate
|
|
||||||
pnpm run db:push
|
|
||||||
pnpm run db:studio
|
|
||||||
pnpm run docker:up:db
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Revalidation
|
|
||||||
|
|
||||||
Arquivo: `src/shared/lib/actions/helpers.ts`
|
|
||||||
|
|
||||||
- atualizar sempre os paths em ingles
|
|
||||||
- lembrar de manter a tag `"dashboard"` para invalidacoes financeiras
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Auth
|
|
||||||
|
|
||||||
- `getUser()` / `getUserId()` em `src/shared/lib/auth/server.ts`
|
|
||||||
- sessao deduplicada por request com `React.cache()`
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Dashboard Fetcher
|
|
||||||
|
|
||||||
Padrao recomendado:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
import { getAdminPayerId } from "@/shared/lib/payers/get-admin-id";
|
|
||||||
|
|
||||||
export async function fetchData(userId: string, period: string) {
|
|
||||||
const adminPayerId = await getAdminPayerId(userId);
|
|
||||||
if (!adminPayerId) return [];
|
|
||||||
|
|
||||||
return db.query.transactions.findMany({
|
|
||||||
where: /* sempre com userId + adminPayerId + period */,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## New Feature Checklist
|
|
||||||
|
|
||||||
1. Criar a rota fina em `src/app/(dashboard)/<feature>/page.tsx`
|
|
||||||
2. Criar a feature em `src/features/<feature>/`
|
|
||||||
3. Separar:
|
|
||||||
- `components/`
|
|
||||||
- `queries.ts` (entry point de leitura)
|
|
||||||
- `actions.ts` (entry point de Server Actions; vira barrel quando crescer e migrar para `actions/`)
|
|
||||||
- `lib/` para helpers internos, sub-queries por tópico, types e constantes da feature
|
|
||||||
- `types.ts` ou `schemas.ts` quando fizer sentido (alternativa a `lib/`)
|
|
||||||
- `hooks/` quando houver hooks específicos da feature
|
|
||||||
4. Extrair para `src/shared/` tudo que for reutilizavel
|
|
||||||
5. Atualizar navegacao e `revalidateForEntity()` se a feature tiver CRUD
|
|
||||||
6. Rodar:
|
|
||||||
- `pnpm exec next typegen`
|
|
||||||
- `pnpm exec tsc --noEmit`
|
|
||||||
- `pnpm run lint`
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Security Rules
|
|
||||||
|
|
||||||
Regras aplicadas automaticamente ao gerar codigo.
|
|
||||||
|
|
||||||
### Secrets
|
|
||||||
Nunca colocar API keys, credenciais de banco ou tokens em codigo frontend. Evitar variaveis prefixadas com `NEXT_PUBLIC_` para dados sensiveis — estas sao bundladas no cliente. Usar variaveis server-side apenas. `.env` deve estar no `.gitignore` antes do primeiro commit. `.env.example` deve ter apenas placeholders.
|
|
||||||
|
|
||||||
### Autenticacao & Autorizacao
|
|
||||||
Toda rota protegida em `src/app/api/` requer `getUser()` ou `getOptionalUserSession()` antes de qualquer logica, retornando 401 para nao autenticados. Rotas com IDs de recursos devem verificar ownership: `eq(table.userId, userId)`. Rotas admin devem checar role e retornar 403 para nao-admins. Session cookies em Better Auth ja tem `httpOnly`, `secure` e `sameSite` configurados — nao alterar.
|
|
||||||
|
|
||||||
### Input & Output
|
|
||||||
Usar Drizzle ORM (parametrizado por padrao) — nunca concatenar input de usuario em SQL. Validar todo input com Zod antes de usar. Upload de arquivos: usar whitelist de MIME types (`ALLOWED_MIME_TYPES`), presigned URLs para S3, token de upload assinado com verificacao pos-upload. Nunca usar `dangerouslySetInnerHTML` com conteudo de usuario.
|
|
||||||
|
|
||||||
### Headers & CSP
|
|
||||||
CSP definida em `src/proxy.ts` via middleware — alterar la, nao em `next.config.ts`. Headers de seguranca (HSTS, X-Frame-Options, etc.) definidos em `next.config.ts`. Nao remover nem enfraquecer essas configuracoes.
|
|
||||||
|
|
||||||
### Rate Limiting
|
|
||||||
Login: 5 tentativas/min. Signup: 3 tentativas/min. API tokens: 100 req/min (inbox), 20 req/min (batch). Configurado em `src/shared/lib/auth/config.ts` e nas rotas de inbox. Nao remover.
|
|
||||||
|
|
||||||
### Tratamento de Erros
|
|
||||||
Erros nao devem expor stack traces, paths ou nomes de bibliotecas ao cliente. Usar mensagens genericas: `"Algo deu errado"`. Logar detalhes apenas no servidor com `console.error()`.
|
|
||||||
|
|
||||||
### Dependencias
|
|
||||||
Verificar pacotes novos sugeridos pela IA em npmjs.com antes de instalar. Red flags: menos de 1.000 downloads/semana, publicado nos ultimos 30 dias, nome muito parecido com pacote popular. Rodar `pnpm audit` periodicamente.
|
|
||||||
|
|
||||||
---
|
|
||||||
10
README.md
10
README.md
@@ -10,7 +10,7 @@
|
|||||||
|
|
||||||
> **Não há versão online hospedada.** Você precisa clonar o repositório e rodar localmente ou no seu próprio servidor.
|
> **Não há versão online hospedada.** Você precisa clonar o repositório e rodar localmente ou no seu próprio servidor.
|
||||||
|
|
||||||
[](CHANGELOG.md)
|
[](CHANGELOG.md)
|
||||||
[](https://nextjs.org/)
|
[](https://nextjs.org/)
|
||||||
[](https://www.typescriptlang.org/)
|
[](https://www.typescriptlang.org/)
|
||||||
[](https://www.postgresql.org/)
|
[](https://www.postgresql.org/)
|
||||||
@@ -65,7 +65,7 @@ A ideia é simples: ter um lugar onde consigo ver todas as minhas contas, cartõ
|
|||||||
|
|
||||||
### Funcionalidades
|
### Funcionalidades
|
||||||
|
|
||||||
💰 **Contas e transações** — Contas bancárias, cartões, dinheiro. Receitas, despesas, rendimentos e transferências. Categorização, divisão de lançamentos entre várias pessoas, filtros combináveis com intervalo de datas, extratos detalhados com identificação visual clara da conta e importação de extratos OFX e XLS/XLSX com detecção automática de categoria.
|
💰 **Contas e transações** — Contas bancárias, cartões, dinheiro. Receitas, despesas, rendimentos e transferências. Categorização, divisão de lançamentos entre várias pessoas, filtros combináveis com intervalo de datas, extratos detalhados com identificação visual clara da conta e importação de extratos OFX e XLS/XLSX com detecção automática de categoria e deduplicação resiliente a identificadores bancários repetidos.
|
||||||
|
|
||||||
📊 **Dashboard e relatórios** — Widgets personalizáveis com listas consistentes, métricas com atalhos para lançamentos, gráficos de evolução, comparativos por categoria, tendências, uso de cartões, top estabelecimentos e navegação direta entre meses pelo seletor de período. Exportação em PDF e Excel.
|
📊 **Dashboard e relatórios** — Widgets personalizáveis com listas consistentes, métricas com atalhos para lançamentos, gráficos de evolução, comparativos por categoria, tendências, uso de cartões, top estabelecimentos e navegação direta entre meses pelo seletor de período. Exportação em PDF e Excel.
|
||||||
|
|
||||||
@@ -89,7 +89,7 @@ A ideia é simples: ter um lugar onde consigo ver todas as minhas contas, cartõ
|
|||||||
<img src="./public/images/companion-preview-light.webp" alt="OpenMonetis Companion" width="300" height="600" />
|
<img src="./public/images/companion-preview-light.webp" alt="OpenMonetis Companion" width="300" height="600" />
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
⚙️ **Personalização** — Tema dark/light, modo privacidade, ordem das colunas, exibição de anotações, tamanho máximo de anexos, resumo opcional no modal de lançamento e changelog visual para acompanhar as novidades do app.
|
⚙️ **Personalização** — Tema dark/light, modo privacidade, ordem das colunas, agrupamento por data em lançamentos, exibição de anotações, tamanho máximo de anexos, resumo opcional no modal de lançamento e changelog visual para acompanhar as novidades do app.
|
||||||
|
|
||||||
### Stack técnica
|
### Stack técnica
|
||||||
|
|
||||||
@@ -628,8 +628,8 @@ Antes de começar, leia o [`CLAUDE.md`](CLAUDE.md) — ele documenta a arquitetu
|
|||||||
As validações rodam em pull requests e em cada push na `main`. A publicação só começa quando uma tag SemVer aponta para um commit validado e a versão da tag corresponde ao `package.json` e ao `CHANGELOG.md`.
|
As validações rodam em pull requests e em cada push na `main`. A publicação só começa quando uma tag SemVer aponta para um commit validado e a versão da tag corresponde ao `package.json` e ao `CHANGELOG.md`.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git tag -a v2.7.9 -m "v2.7.9"
|
git tag -a v2.7.13 -m "v2.7.13"
|
||||||
git push origin v2.7.9
|
git push origin v2.7.13
|
||||||
```
|
```
|
||||||
|
|
||||||
O workflow da tag valida o código, publica as imagens Docker versionadas e `latest` e, somente depois, cria a GitHub Release com as notas do changelog.
|
O workflow da tag valida o código, publica as imagens Docker versionadas e `latest` e, somente depois, cria a GitHub Release com as notas do changelog.
|
||||||
|
|||||||
1
drizzle/0032_bumpy_spencer_smythe.sql
Normal file
1
drizzle/0032_bumpy_spencer_smythe.sql
Normal file
@@ -0,0 +1 @@
|
|||||||
|
ALTER TABLE "preferencias_usuario" ADD COLUMN "ocultar_parcelas_antecipadas" boolean DEFAULT false NOT NULL;
|
||||||
1
drizzle/0033_demonic_supreme_intelligence.sql
Normal file
1
drizzle/0033_demonic_supreme_intelligence.sql
Normal file
@@ -0,0 +1 @@
|
|||||||
|
ALTER TABLE "preferencias_usuario" ADD COLUMN "agrupar_lancamentos_por_data" boolean DEFAULT true NOT NULL;
|
||||||
3
drizzle/0034_superb_blonde_phantom.sql
Normal file
3
drizzle/0034_superb_blonde_phantom.sql
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
DROP INDEX "lancamentos_ofx_fit_id_user_id_idx";--> statement-breakpoint
|
||||||
|
ALTER TABLE "lancamentos" ADD COLUMN "ofx_import_fingerprint" text;--> statement-breakpoint
|
||||||
|
CREATE UNIQUE INDEX "lancamentos_ofx_import_fingerprint_user_id_idx" ON "lancamentos" USING btree ("user_id","ofx_import_fingerprint") WHERE ofx_import_fingerprint IS NOT NULL;
|
||||||
2995
drizzle/meta/0032_snapshot.json
Normal file
2995
drizzle/meta/0032_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
3002
drizzle/meta/0033_snapshot.json
Normal file
3002
drizzle/meta/0033_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
3008
drizzle/meta/0034_snapshot.json
Normal file
3008
drizzle/meta/0034_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
@@ -218,6 +218,27 @@
|
|||||||
"when": 1782051007412,
|
"when": 1782051007412,
|
||||||
"tag": "0031_lame_cerise",
|
"tag": "0031_lame_cerise",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 32,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1782569103402,
|
||||||
|
"tag": "0032_bumpy_spencer_smythe",
|
||||||
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 33,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1782685465530,
|
||||||
|
"tag": "0033_demonic_supreme_intelligence",
|
||||||
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 34,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1786299746933,
|
||||||
|
"tag": "0034_superb_blonde_phantom",
|
||||||
|
"breakpoints": true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,23 +4,34 @@ import type { NextConfig } from "next";
|
|||||||
// Carregar variáveis de ambiente explicitamente
|
// Carregar variáveis de ambiente explicitamente
|
||||||
dotenv.config();
|
dotenv.config();
|
||||||
|
|
||||||
|
type RemotePattern = NonNullable<
|
||||||
|
NonNullable<NextConfig["images"]>["remotePatterns"]
|
||||||
|
>[number];
|
||||||
|
|
||||||
|
const imageRemotePatterns: RemotePattern[] = [
|
||||||
|
{
|
||||||
|
protocol: "https",
|
||||||
|
hostname: "lh3.googleusercontent.com",
|
||||||
|
pathname: "/**",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
protocol: "https",
|
||||||
|
hostname: "img.logo.dev",
|
||||||
|
pathname: "/**",
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
const nextConfig: NextConfig = {
|
const nextConfig: NextConfig = {
|
||||||
output: "standalone",
|
output: "standalone",
|
||||||
cacheComponents: true,
|
cacheComponents: true,
|
||||||
reactCompiler: true,
|
reactCompiler: true,
|
||||||
images: {
|
images: {
|
||||||
remotePatterns: [
|
remotePatterns: imageRemotePatterns,
|
||||||
new URL("https://lh3.googleusercontent.com/**"),
|
|
||||||
{ protocol: "https", hostname: "**" },
|
|
||||||
{ protocol: "http", hostname: "**" },
|
|
||||||
],
|
|
||||||
},
|
},
|
||||||
devIndicators: {
|
devIndicators: {
|
||||||
position: "bottom-right",
|
position: "bottom-right",
|
||||||
},
|
},
|
||||||
experimental: {
|
experimental: {
|
||||||
prefetchInlining: true,
|
|
||||||
turbopackFileSystemCacheForDev: true,
|
|
||||||
optimizePackageImports: ["@remixicon/react"],
|
optimizePackageImports: ["@remixicon/react"],
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|||||||
46
package.json
46
package.json
@@ -1,10 +1,10 @@
|
|||||||
{
|
{
|
||||||
"name": "openmonetis",
|
"name": "openmonetis",
|
||||||
"version": "2.7.9",
|
"version": "2.7.13",
|
||||||
"private": true,
|
"private": true,
|
||||||
"packageManager": "pnpm@11.1.3",
|
"packageManager": "pnpm@11.1.3",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "next dev --turbopack",
|
"dev": "next dev",
|
||||||
"db:seed": "tsx scripts/mock-data.ts",
|
"db:seed": "tsx scripts/mock-data.ts",
|
||||||
"build": "next build",
|
"build": "next build",
|
||||||
"start": "next start",
|
"start": "next start",
|
||||||
@@ -31,32 +31,32 @@
|
|||||||
"mockup": "tsx scripts/mock-data.ts"
|
"mockup": "tsx scripts/mock-data.ts"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ai-sdk/anthropic": "^3.0.81",
|
"@ai-sdk/anthropic": "^3.0.88",
|
||||||
"@ai-sdk/google": "^3.0.80",
|
"@ai-sdk/google": "^3.0.85",
|
||||||
"@ai-sdk/openai": "^3.0.67",
|
"@ai-sdk/openai": "^3.0.76",
|
||||||
"@ai-sdk/openai-compatible": "^2.0.48",
|
"@ai-sdk/openai-compatible": "^2.0.53",
|
||||||
"@aws-sdk/client-s3": "^3.1059.0",
|
"@aws-sdk/client-s3": "^3.1075.0",
|
||||||
"@aws-sdk/s3-request-presigner": "^3.1059.0",
|
"@aws-sdk/s3-request-presigner": "^3.1075.0",
|
||||||
"@better-auth/passkey": "^1.6.14",
|
"@better-auth/passkey": "^1.6.22",
|
||||||
"@dnd-kit/core": "^6.3.1",
|
"@dnd-kit/core": "^6.3.1",
|
||||||
"@dnd-kit/sortable": "^10.0.0",
|
"@dnd-kit/sortable": "^10.0.0",
|
||||||
"@dnd-kit/utilities": "^3.2.2",
|
"@dnd-kit/utilities": "^3.2.2",
|
||||||
"@openrouter/ai-sdk-provider": "^2.9.0",
|
"@openrouter/ai-sdk-provider": "^2.10.0",
|
||||||
"@radix-ui/react-alert-dialog": "1.1.15",
|
"@radix-ui/react-alert-dialog": "1.1.15",
|
||||||
"@radix-ui/react-avatar": "1.1.11",
|
"@radix-ui/react-avatar": "1.1.11",
|
||||||
"@radix-ui/react-checkbox": "1.3.3",
|
"@radix-ui/react-checkbox": "1.3.3",
|
||||||
"@radix-ui/react-collapsible": "1.1.12",
|
"@radix-ui/react-collapsible": "1.1.12",
|
||||||
"@radix-ui/react-dialog": "1.1.15",
|
"@radix-ui/react-dialog": "1.1.15",
|
||||||
"@radix-ui/react-dropdown-menu": "2.1.16",
|
"@radix-ui/react-dropdown-menu": "2.1.16",
|
||||||
"@radix-ui/react-hover-card": "^1.1.15",
|
"@radix-ui/react-hover-card": "^1.1.17",
|
||||||
"@radix-ui/react-label": "2.1.8",
|
"@radix-ui/react-label": "2.1.8",
|
||||||
"@radix-ui/react-navigation-menu": "^1.2.14",
|
"@radix-ui/react-navigation-menu": "^1.2.16",
|
||||||
"@radix-ui/react-popover": "^1.1.15",
|
"@radix-ui/react-popover": "^1.1.17",
|
||||||
"@radix-ui/react-progress": "1.1.8",
|
"@radix-ui/react-progress": "1.1.8",
|
||||||
"@radix-ui/react-radio-group": "^1.3.8",
|
"@radix-ui/react-radio-group": "^1.4.1",
|
||||||
"@radix-ui/react-select": "2.2.6",
|
"@radix-ui/react-select": "2.2.6",
|
||||||
"@radix-ui/react-separator": "1.1.8",
|
"@radix-ui/react-separator": "1.1.8",
|
||||||
"@radix-ui/react-slider": "^1.3.6",
|
"@radix-ui/react-slider": "^1.4.1",
|
||||||
"@radix-ui/react-slot": "1.2.4",
|
"@radix-ui/react-slot": "1.2.4",
|
||||||
"@radix-ui/react-switch": "1.2.6",
|
"@radix-ui/react-switch": "1.2.6",
|
||||||
"@radix-ui/react-tabs": "1.1.13",
|
"@radix-ui/react-tabs": "1.1.13",
|
||||||
@@ -64,11 +64,11 @@
|
|||||||
"@radix-ui/react-toggle-group": "1.1.11",
|
"@radix-ui/react-toggle-group": "1.1.11",
|
||||||
"@radix-ui/react-tooltip": "1.2.8",
|
"@radix-ui/react-tooltip": "1.2.8",
|
||||||
"@remixicon/react": "4.9.0",
|
"@remixicon/react": "4.9.0",
|
||||||
"@tanstack/react-query": "^5.101.0",
|
"@tanstack/react-query": "^5.101.1",
|
||||||
"@tanstack/react-table": "8.21.3",
|
"@tanstack/react-table": "8.21.3",
|
||||||
"@tanstack/react-virtual": "^3.14.2",
|
"@tanstack/react-virtual": "^3.14.4",
|
||||||
"ai": "^6.0.195",
|
"ai": "^6.0.213",
|
||||||
"better-auth": "1.6.14",
|
"better-auth": "1.6.22",
|
||||||
"canvas-confetti": "^1.9.4",
|
"canvas-confetti": "^1.9.4",
|
||||||
"class-variance-authority": "0.7.1",
|
"class-variance-authority": "0.7.1",
|
||||||
"clsx": "2.1.1",
|
"clsx": "2.1.1",
|
||||||
@@ -78,7 +78,7 @@
|
|||||||
"exceljs": "^4.4.0",
|
"exceljs": "^4.4.0",
|
||||||
"jspdf": "^4.2.1",
|
"jspdf": "^4.2.1",
|
||||||
"jspdf-autotable": "^5.0.8",
|
"jspdf-autotable": "^5.0.8",
|
||||||
"next": "16.2.7",
|
"next": "16.3.0",
|
||||||
"next-themes": "0.4.6",
|
"next-themes": "0.4.6",
|
||||||
"pdfjs-dist": "^6.0.227",
|
"pdfjs-dist": "^6.0.227",
|
||||||
"pg": "8.21.0",
|
"pg": "8.21.0",
|
||||||
@@ -86,7 +86,7 @@
|
|||||||
"react-day-picker": "^10.0.1",
|
"react-day-picker": "^10.0.1",
|
||||||
"react-dom": "19.2.7",
|
"react-dom": "19.2.7",
|
||||||
"recharts": "3.8.1",
|
"recharts": "3.8.1",
|
||||||
"resend": "^6.12.4",
|
"resend": "^6.16.0",
|
||||||
"sonner": "2.0.7",
|
"sonner": "2.0.7",
|
||||||
"tailwind-merge": "3.6.0",
|
"tailwind-merge": "3.6.0",
|
||||||
"tw-animate-css": "^1.4.0",
|
"tw-animate-css": "^1.4.0",
|
||||||
@@ -105,9 +105,9 @@
|
|||||||
"babel-plugin-react-compiler": "^1.0.0",
|
"babel-plugin-react-compiler": "^1.0.0",
|
||||||
"dotenv": "^17.4.2",
|
"dotenv": "^17.4.2",
|
||||||
"drizzle-kit": "0.31.10",
|
"drizzle-kit": "0.31.10",
|
||||||
"knip": "^6.15.0",
|
"knip": "^6.22.0",
|
||||||
"tailwindcss": "4.3.0",
|
"tailwindcss": "4.3.0",
|
||||||
"tsx": "4.22.4",
|
"tsx": "4.22.4",
|
||||||
"typescript": "6.0.3"
|
"typescript": "7.0.2"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
3358
pnpm-lock.yaml
generated
3358
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@@ -109,6 +109,8 @@ export default async function Page({ params, searchParams }: PageProps) {
|
|||||||
filters: searchFilters,
|
filters: searchFilters,
|
||||||
slugMaps,
|
slugMaps,
|
||||||
accountId: account.id,
|
accountId: account.id,
|
||||||
|
hideAnticipatedInstallments:
|
||||||
|
userPreferences?.hideAnticipatedInstallments ?? false,
|
||||||
});
|
});
|
||||||
|
|
||||||
const transactionsPage = await fetchAccountTransactionsPage(
|
const transactionsPage = await fetchAccountTransactionsPage(
|
||||||
@@ -233,6 +235,9 @@ export default async function Page({ params, searchParams }: PageProps) {
|
|||||||
)}
|
)}
|
||||||
noteAsColumn={userPreferences?.statementNoteAsColumn ?? false}
|
noteAsColumn={userPreferences?.statementNoteAsColumn ?? false}
|
||||||
columnOrder={userPreferences?.transactionsColumnOrder ?? null}
|
columnOrder={userPreferences?.transactionsColumnOrder ?? null}
|
||||||
|
groupTransactionsByDate={
|
||||||
|
userPreferences?.groupTransactionsByDate ?? true
|
||||||
|
}
|
||||||
attachmentMaxSizeMb={userPreferences?.attachmentMaxSizeMb ?? 50}
|
attachmentMaxSizeMb={userPreferences?.attachmentMaxSizeMb ?? 50}
|
||||||
/>
|
/>
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { connection } from "next/server";
|
import { connection } from "next/server";
|
||||||
import { AttachmentsPage } from "@/features/attachments/components/attachments-page";
|
import { AttachmentsPage } from "@/features/attachments/components/attachments-page";
|
||||||
import { fetchAttachmentsPageData } from "@/features/attachments/queries";
|
import { fetchAttachmentsPageData } from "@/features/attachments/queries";
|
||||||
|
import { ContentErrorBoundary } from "@/shared/components/feedback/content-error-boundary";
|
||||||
import { getUserId } from "@/shared/lib/auth/server";
|
import { getUserId } from "@/shared/lib/auth/server";
|
||||||
import { parsePeriodParam } from "@/shared/utils/period";
|
import { parsePeriodParam } from "@/shared/utils/period";
|
||||||
|
|
||||||
@@ -19,7 +20,18 @@ const getSingleParam = (
|
|||||||
return Array.isArray(value) ? (value[0] ?? null) : value;
|
return Array.isArray(value) ? (value[0] ?? null) : value;
|
||||||
};
|
};
|
||||||
|
|
||||||
export default async function Page({ searchParams }: PageProps) {
|
export default function Page({ searchParams }: PageProps) {
|
||||||
|
return (
|
||||||
|
<ContentErrorBoundary
|
||||||
|
title="Não foi possível carregar os anexos"
|
||||||
|
description="Os documentos e comprovantes não puderam ser carregados agora."
|
||||||
|
>
|
||||||
|
<AttachmentsContent searchParams={searchParams} />
|
||||||
|
</ContentErrorBoundary>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function AttachmentsContent({ searchParams }: PageProps) {
|
||||||
await connection();
|
await connection();
|
||||||
const userId = await getUserId();
|
const userId = await getUserId();
|
||||||
const resolvedSearchParams = searchParams ? await searchParams : undefined;
|
const resolvedSearchParams = searchParams ? await searchParams : undefined;
|
||||||
|
|||||||
@@ -82,6 +82,8 @@ export default async function Page({ params, searchParams }: PageProps) {
|
|||||||
filters: searchFilters,
|
filters: searchFilters,
|
||||||
slugMaps,
|
slugMaps,
|
||||||
cardId: card.id,
|
cardId: card.id,
|
||||||
|
hideAnticipatedInstallments:
|
||||||
|
userPreferences?.hideAnticipatedInstallments ?? false,
|
||||||
});
|
});
|
||||||
|
|
||||||
const transactionRows = await fetchCardTransactions(filters);
|
const transactionRows = await fetchCardTransactions(filters);
|
||||||
@@ -210,6 +212,9 @@ export default async function Page({ params, searchParams }: PageProps) {
|
|||||||
allowCreate
|
allowCreate
|
||||||
noteAsColumn={userPreferences?.statementNoteAsColumn ?? false}
|
noteAsColumn={userPreferences?.statementNoteAsColumn ?? false}
|
||||||
columnOrder={userPreferences?.transactionsColumnOrder ?? null}
|
columnOrder={userPreferences?.transactionsColumnOrder ?? null}
|
||||||
|
groupTransactionsByDate={
|
||||||
|
userPreferences?.groupTransactionsByDate ?? true
|
||||||
|
}
|
||||||
attachmentMaxSizeMb={userPreferences?.attachmentMaxSizeMb ?? 50}
|
attachmentMaxSizeMb={userPreferences?.attachmentMaxSizeMb ?? 50}
|
||||||
defaultCardId={card.id}
|
defaultCardId={card.id}
|
||||||
defaultPaymentMethod="Cartão de crédito"
|
defaultPaymentMethod="Cartão de crédito"
|
||||||
|
|||||||
@@ -41,13 +41,17 @@ export default async function Page({ params, searchParams }: PageProps) {
|
|||||||
const periodoParam = getSingleParam(resolvedSearchParams, "periodo");
|
const periodoParam = getSingleParam(resolvedSearchParams, "periodo");
|
||||||
const { period: selectedPeriod } = parsePeriodParam(periodoParam);
|
const { period: selectedPeriod } = parsePeriodParam(periodoParam);
|
||||||
|
|
||||||
const [detail, filterSources, estabelecimentos, userPreferences] =
|
const [filterSources, estabelecimentos, userPreferences] = await Promise.all([
|
||||||
await Promise.all([
|
|
||||||
fetchCategoryDetails(userId, categoryId, selectedPeriod),
|
|
||||||
fetchTransactionFilterSources(userId),
|
fetchTransactionFilterSources(userId),
|
||||||
fetchRecentEstablishments(userId),
|
fetchRecentEstablishments(userId),
|
||||||
fetchUserPreferences(userId),
|
fetchUserPreferences(userId),
|
||||||
]);
|
]);
|
||||||
|
const detail = await fetchCategoryDetails(
|
||||||
|
userId,
|
||||||
|
categoryId,
|
||||||
|
selectedPeriod,
|
||||||
|
userPreferences?.hideAnticipatedInstallments ?? false,
|
||||||
|
);
|
||||||
|
|
||||||
if (!detail) {
|
if (!detail) {
|
||||||
notFound();
|
notFound();
|
||||||
@@ -101,6 +105,9 @@ export default async function Page({ params, searchParams }: PageProps) {
|
|||||||
allowCreate={true}
|
allowCreate={true}
|
||||||
noteAsColumn={userPreferences?.statementNoteAsColumn ?? false}
|
noteAsColumn={userPreferences?.statementNoteAsColumn ?? false}
|
||||||
columnOrder={userPreferences?.transactionsColumnOrder ?? null}
|
columnOrder={userPreferences?.transactionsColumnOrder ?? null}
|
||||||
|
groupTransactionsByDate={
|
||||||
|
userPreferences?.groupTransactionsByDate ?? true
|
||||||
|
}
|
||||||
attachmentMaxSizeMb={userPreferences?.attachmentMaxSizeMb ?? 50}
|
attachmentMaxSizeMb={userPreferences?.attachmentMaxSizeMb ?? 50}
|
||||||
/>
|
/>
|
||||||
</main>
|
</main>
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { extractDashboardLogoNames } from "@/features/dashboard/lib/extract-logo
|
|||||||
import { fetchDashboardPageData } from "@/features/dashboard/page-data-queries";
|
import { fetchDashboardPageData } from "@/features/dashboard/page-data-queries";
|
||||||
import { getSingleParam } from "@/features/transactions/lib/page-helpers";
|
import { getSingleParam } from "@/features/transactions/lib/page-helpers";
|
||||||
import { LogoPrefetchProvider } from "@/shared/components/entity-avatar";
|
import { LogoPrefetchProvider } from "@/shared/components/entity-avatar";
|
||||||
|
import { ContentErrorBoundary } from "@/shared/components/feedback/content-error-boundary";
|
||||||
import MonthNavigation from "@/shared/components/month-picker/month-navigation";
|
import MonthNavigation from "@/shared/components/month-picker/month-navigation";
|
||||||
import { getUser } from "@/shared/lib/auth/server";
|
import { getUser } from "@/shared/lib/auth/server";
|
||||||
import { prefetchLogoMappings } from "@/shared/lib/logo/prefetch-server";
|
import { prefetchLogoMappings } from "@/shared/lib/logo/prefetch-server";
|
||||||
@@ -17,7 +18,18 @@ type PageProps = {
|
|||||||
searchParams?: PageSearchParams;
|
searchParams?: PageSearchParams;
|
||||||
};
|
};
|
||||||
|
|
||||||
export default async function Page({ searchParams }: PageProps) {
|
export default function Page({ searchParams }: PageProps) {
|
||||||
|
return (
|
||||||
|
<ContentErrorBoundary
|
||||||
|
title="Não foi possível carregar o dashboard"
|
||||||
|
description="Seus dados financeiros não puderam ser carregados agora."
|
||||||
|
>
|
||||||
|
<DashboardContent searchParams={searchParams} />
|
||||||
|
</ContentErrorBoundary>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function DashboardContent({ searchParams }: PageProps) {
|
||||||
await connection();
|
await connection();
|
||||||
const user = await getUser();
|
const user = await getUser();
|
||||||
const resolvedSearchParams = searchParams ? await searchParams : undefined;
|
const resolvedSearchParams = searchParams ? await searchParams : undefined;
|
||||||
@@ -41,11 +53,20 @@ export default async function Page({ searchParams }: PageProps) {
|
|||||||
<main className="flex flex-col gap-4">
|
<main className="flex flex-col gap-4">
|
||||||
<DashboardWelcome name={user.name} />
|
<DashboardWelcome name={user.name} />
|
||||||
<MonthNavigation />
|
<MonthNavigation />
|
||||||
|
<ContentErrorBoundary
|
||||||
|
title="Não foi possível exibir o resumo"
|
||||||
|
description="Os indicadores do período não puderam ser exibidos agora."
|
||||||
|
>
|
||||||
<DashboardMetricsCards
|
<DashboardMetricsCards
|
||||||
metrics={dashboardData.metrics}
|
metrics={dashboardData.metrics}
|
||||||
period={selectedPeriod}
|
period={selectedPeriod}
|
||||||
adminPayerSlug={adminPayerSlug}
|
adminPayerSlug={adminPayerSlug}
|
||||||
/>
|
/>
|
||||||
|
</ContentErrorBoundary>
|
||||||
|
<ContentErrorBoundary
|
||||||
|
title="Não foi possível exibir os widgets"
|
||||||
|
description="Os detalhes do dashboard não puderam ser exibidos agora."
|
||||||
|
>
|
||||||
<LogoPrefetchProvider mappings={logoMappings}>
|
<LogoPrefetchProvider mappings={logoMappings}>
|
||||||
<DashboardGridEditable
|
<DashboardGridEditable
|
||||||
data={dashboardData}
|
data={dashboardData}
|
||||||
@@ -54,6 +75,7 @@ export default async function Page({ searchParams }: PageProps) {
|
|||||||
quickActionOptions={quickActionOptions}
|
quickActionOptions={quickActionOptions}
|
||||||
/>
|
/>
|
||||||
</LogoPrefetchProvider>
|
</LogoPrefetchProvider>
|
||||||
|
</ContentErrorBoundary>
|
||||||
</main>
|
</main>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { connection } from "next/server";
|
import { connection } from "next/server";
|
||||||
import { InsightsPage } from "@/features/insights/components/insights-page";
|
import { InsightsPage } from "@/features/insights/components/insights-page";
|
||||||
|
import { ContentErrorBoundary } from "@/shared/components/feedback/content-error-boundary";
|
||||||
import MonthNavigation from "@/shared/components/month-picker/month-navigation";
|
import MonthNavigation from "@/shared/components/month-picker/month-navigation";
|
||||||
import { parsePeriodParam } from "@/shared/utils/period";
|
import { parsePeriodParam } from "@/shared/utils/period";
|
||||||
|
|
||||||
@@ -18,7 +19,18 @@ const getSingleParam = (
|
|||||||
return Array.isArray(value) ? (value[0] ?? null) : value;
|
return Array.isArray(value) ? (value[0] ?? null) : value;
|
||||||
};
|
};
|
||||||
|
|
||||||
export default async function Page({ searchParams }: PageProps) {
|
export default function Page({ searchParams }: PageProps) {
|
||||||
|
return (
|
||||||
|
<ContentErrorBoundary
|
||||||
|
title="Não foi possível carregar os Insights"
|
||||||
|
description="As análises financeiras não puderam ser carregadas agora."
|
||||||
|
>
|
||||||
|
<InsightsContent searchParams={searchParams} />
|
||||||
|
</ContentErrorBoundary>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function InsightsContent({ searchParams }: PageProps) {
|
||||||
await connection();
|
await connection();
|
||||||
const resolvedSearchParams = searchParams ? await searchParams : undefined;
|
const resolvedSearchParams = searchParams ? await searchParams : undefined;
|
||||||
const periodoParam = getSingleParam(resolvedSearchParams, "periodo");
|
const periodoParam = getSingleParam(resolvedSearchParams, "periodo");
|
||||||
|
|||||||
@@ -131,6 +131,7 @@ export default async function Page({ params, searchParams }: PageProps) {
|
|||||||
...EMPTY_FILTERS,
|
...EMPTY_FILTERS,
|
||||||
searchFilter: allSearchFilters.searchFilter, // Permitir busca mesmo em modo read-only
|
searchFilter: allSearchFilters.searchFilter, // Permitir busca mesmo em modo read-only
|
||||||
};
|
};
|
||||||
|
const userPreferences = await fetchUserPreferences(userId);
|
||||||
|
|
||||||
let filterSources: Awaited<
|
let filterSources: Awaited<
|
||||||
ReturnType<typeof fetchTransactionFilterSources>
|
ReturnType<typeof fetchTransactionFilterSources>
|
||||||
@@ -163,6 +164,8 @@ export default async function Page({ params, searchParams }: PageProps) {
|
|||||||
filters: searchFilters,
|
filters: searchFilters,
|
||||||
slugMaps,
|
slugMaps,
|
||||||
payerId: pagador.id,
|
payerId: pagador.id,
|
||||||
|
hideAnticipatedInstallments:
|
||||||
|
userPreferences?.hideAnticipatedInstallments ?? false,
|
||||||
});
|
});
|
||||||
|
|
||||||
const sharesPromise = canEdit
|
const sharesPromise = canEdit
|
||||||
@@ -184,7 +187,6 @@ export default async function Page({ params, searchParams }: PageProps) {
|
|||||||
shareRows,
|
shareRows,
|
||||||
currentUserShare,
|
currentUserShare,
|
||||||
estabelecimentos,
|
estabelecimentos,
|
||||||
userPreferences,
|
|
||||||
] = await Promise.all([
|
] = await Promise.all([
|
||||||
fetchPayerTransactions(filters),
|
fetchPayerTransactions(filters),
|
||||||
fetchPayerMonthlyBreakdown({
|
fetchPayerMonthlyBreakdown({
|
||||||
@@ -220,7 +222,6 @@ export default async function Page({ params, searchParams }: PageProps) {
|
|||||||
sharesPromise,
|
sharesPromise,
|
||||||
currentUserSharePromise,
|
currentUserSharePromise,
|
||||||
fetchRecentEstablishments(userId),
|
fetchRecentEstablishments(userId),
|
||||||
fetchUserPreferences(userId),
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const mappedTransactions = mapTransactionsData(transactionRows);
|
const mappedTransactions = mapTransactionsData(transactionRows);
|
||||||
@@ -407,6 +408,9 @@ export default async function Page({ params, searchParams }: PageProps) {
|
|||||||
allowCreate={canEdit}
|
allowCreate={canEdit}
|
||||||
noteAsColumn={userPreferences?.statementNoteAsColumn ?? false}
|
noteAsColumn={userPreferences?.statementNoteAsColumn ?? false}
|
||||||
columnOrder={userPreferences?.transactionsColumnOrder ?? null}
|
columnOrder={userPreferences?.transactionsColumnOrder ?? null}
|
||||||
|
groupTransactionsByDate={
|
||||||
|
userPreferences?.groupTransactionsByDate ?? true
|
||||||
|
}
|
||||||
attachmentMaxSizeMb={userPreferences?.attachmentMaxSizeMb ?? 50}
|
attachmentMaxSizeMb={userPreferences?.attachmentMaxSizeMb ?? 50}
|
||||||
importPayerOptions={loggedUserOptionSets?.payerOptions}
|
importPayerOptions={loggedUserOptionSets?.payerOptions}
|
||||||
importSplitPayerOptions={
|
importSplitPayerOptions={
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { CardTopExpenses } from "@/features/reports/components/cards/card-top-ex
|
|||||||
import { CardUsageChart } from "@/features/reports/components/cards/card-usage-chart";
|
import { CardUsageChart } from "@/features/reports/components/cards/card-usage-chart";
|
||||||
import { CardsOverview } from "@/features/reports/components/cards/cards-overview";
|
import { CardsOverview } from "@/features/reports/components/cards/cards-overview";
|
||||||
import { fetchCartoesReportData } from "@/features/reports/lib/cards-report-queries";
|
import { fetchCartoesReportData } from "@/features/reports/lib/cards-report-queries";
|
||||||
|
import { ContentErrorBoundary } from "@/shared/components/feedback/content-error-boundary";
|
||||||
import MonthNavigation from "@/shared/components/month-picker/month-navigation";
|
import MonthNavigation from "@/shared/components/month-picker/month-navigation";
|
||||||
import { Card } from "@/shared/components/ui/card";
|
import { Card } from "@/shared/components/ui/card";
|
||||||
import { getUser } from "@/shared/lib/auth/server";
|
import { getUser } from "@/shared/lib/auth/server";
|
||||||
@@ -26,9 +27,18 @@ const getSingleParam = (
|
|||||||
return Array.isArray(value) ? (value[0] ?? null) : value;
|
return Array.isArray(value) ? (value[0] ?? null) : value;
|
||||||
};
|
};
|
||||||
|
|
||||||
export default async function RelatorioCartoesPage({
|
export default function CardUsagePage({ searchParams }: PageProps) {
|
||||||
searchParams,
|
return (
|
||||||
}: PageProps) {
|
<ContentErrorBoundary
|
||||||
|
title="Não foi possível carregar o uso dos cartões"
|
||||||
|
description="Os dados deste relatório não puderam ser carregados agora."
|
||||||
|
>
|
||||||
|
<CardUsageContent searchParams={searchParams} />
|
||||||
|
</ContentErrorBoundary>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function CardUsageContent({ searchParams }: PageProps) {
|
||||||
await connection();
|
await connection();
|
||||||
const user = await getUser();
|
const user = await getUser();
|
||||||
const resolvedSearchParams = searchParams ? await searchParams : undefined;
|
const resolvedSearchParams = searchParams ? await searchParams : undefined;
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import { fetchCategoryChartData } from "@/features/reports/lib/category-chart-qu
|
|||||||
import { fetchCategoryReport } from "@/features/reports/lib/category-report-queries";
|
import { fetchCategoryReport } from "@/features/reports/lib/category-report-queries";
|
||||||
import { fetchUserCategories } from "@/features/reports/lib/category-trends-queries";
|
import { fetchUserCategories } from "@/features/reports/lib/category-trends-queries";
|
||||||
import { validateDateRange } from "@/features/reports/lib/utils";
|
import { validateDateRange } from "@/features/reports/lib/utils";
|
||||||
|
import { ContentErrorBoundary } from "@/shared/components/feedback/content-error-boundary";
|
||||||
import { getUserId } from "@/shared/lib/auth/server";
|
import { getUserId } from "@/shared/lib/auth/server";
|
||||||
import type { CategoryReportFilters } from "@/shared/lib/types/reports";
|
import type { CategoryReportFilters } from "@/shared/lib/types/reports";
|
||||||
import { addMonthsToPeriod, getCurrentPeriod } from "@/shared/utils/period";
|
import { addMonthsToPeriod, getCurrentPeriod } from "@/shared/utils/period";
|
||||||
@@ -29,7 +30,18 @@ const getSingleParam = (
|
|||||||
return Array.isArray(value) ? (value[0] ?? null) : value;
|
return Array.isArray(value) ? (value[0] ?? null) : value;
|
||||||
};
|
};
|
||||||
|
|
||||||
export default async function Page({ searchParams }: PageProps) {
|
export default function Page({ searchParams }: PageProps) {
|
||||||
|
return (
|
||||||
|
<ContentErrorBoundary
|
||||||
|
title="Não foi possível carregar as tendências"
|
||||||
|
description="A evolução das categorias não pôde ser carregada agora."
|
||||||
|
>
|
||||||
|
<CategoryTrendsContent searchParams={searchParams} />
|
||||||
|
</ContentErrorBoundary>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function CategoryTrendsContent({ searchParams }: PageProps) {
|
||||||
await connection();
|
await connection();
|
||||||
// Get authenticated user
|
// Get authenticated user
|
||||||
const userId = await getUserId();
|
const userId = await getUserId();
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import {
|
|||||||
fetchTopEstablishmentsData,
|
fetchTopEstablishmentsData,
|
||||||
type PeriodFilter,
|
type PeriodFilter,
|
||||||
} from "@/features/reports/establishments/queries";
|
} from "@/features/reports/establishments/queries";
|
||||||
|
import { ContentErrorBoundary } from "@/shared/components/feedback/content-error-boundary";
|
||||||
import { Card } from "@/shared/components/ui/card";
|
import { Card } from "@/shared/components/ui/card";
|
||||||
import { getUser } from "@/shared/lib/auth/server";
|
import { getUser } from "@/shared/lib/auth/server";
|
||||||
import { parsePeriodParam } from "@/shared/utils/period";
|
import { parsePeriodParam } from "@/shared/utils/period";
|
||||||
@@ -34,9 +35,18 @@ const validatePeriodFilter = (value: string | null): PeriodFilter => {
|
|||||||
return "6";
|
return "6";
|
||||||
};
|
};
|
||||||
|
|
||||||
export default async function TopEstablishmentsPage({
|
export default function EstablishmentsPage({ searchParams }: PageProps) {
|
||||||
searchParams,
|
return (
|
||||||
}: PageProps) {
|
<ContentErrorBoundary
|
||||||
|
title="Não foi possível carregar os estabelecimentos"
|
||||||
|
description="Os dados deste relatório não puderam ser carregados agora."
|
||||||
|
>
|
||||||
|
<EstablishmentsContent searchParams={searchParams} />
|
||||||
|
</ContentErrorBoundary>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function EstablishmentsContent({ searchParams }: PageProps) {
|
||||||
await connection();
|
await connection();
|
||||||
const user = await getUser();
|
const user = await getUser();
|
||||||
const resolvedSearchParams = searchParams ? await searchParams : undefined;
|
const resolvedSearchParams = searchParams ? await searchParams : undefined;
|
||||||
|
|||||||
@@ -2,10 +2,22 @@ import { connection } from "next/server";
|
|||||||
import { InstallmentAnalysisPage } from "@/features/dashboard/components/installment-analysis/installment-analysis-page";
|
import { InstallmentAnalysisPage } from "@/features/dashboard/components/installment-analysis/installment-analysis-page";
|
||||||
import { fetchInstallmentAnalysis } from "@/features/dashboard/expenses/installment-analysis-queries";
|
import { fetchInstallmentAnalysis } from "@/features/dashboard/expenses/installment-analysis-queries";
|
||||||
import { LogoPrefetchProvider } from "@/shared/components/entity-avatar";
|
import { LogoPrefetchProvider } from "@/shared/components/entity-avatar";
|
||||||
|
import { ContentErrorBoundary } from "@/shared/components/feedback/content-error-boundary";
|
||||||
import { getUser } from "@/shared/lib/auth/server";
|
import { getUser } from "@/shared/lib/auth/server";
|
||||||
import { prefetchLogoMappings } from "@/shared/lib/logo/prefetch-server";
|
import { prefetchLogoMappings } from "@/shared/lib/logo/prefetch-server";
|
||||||
|
|
||||||
export default async function Page() {
|
export default function Page() {
|
||||||
|
return (
|
||||||
|
<ContentErrorBoundary
|
||||||
|
title="Não foi possível carregar a análise de parcelas"
|
||||||
|
description="Os parcelamentos não puderam ser analisados agora."
|
||||||
|
>
|
||||||
|
<InstallmentAnalysisContent />
|
||||||
|
</ContentErrorBoundary>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function InstallmentAnalysisContent() {
|
||||||
await connection();
|
await connection();
|
||||||
const user = await getUser();
|
const user = await getUser();
|
||||||
const data = await fetchInstallmentAnalysis(user.id);
|
const data = await fetchInstallmentAnalysis(user.id);
|
||||||
|
|||||||
@@ -85,6 +85,12 @@ export default async function Page() {
|
|||||||
showTransactionSummary={
|
showTransactionSummary={
|
||||||
userPreferences?.showTransactionSummary ?? true
|
userPreferences?.showTransactionSummary ?? true
|
||||||
}
|
}
|
||||||
|
groupTransactionsByDate={
|
||||||
|
userPreferences?.groupTransactionsByDate ?? true
|
||||||
|
}
|
||||||
|
hideAnticipatedInstallments={
|
||||||
|
userPreferences?.hideAnticipatedInstallments ?? false
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</Card>
|
</Card>
|
||||||
|
|||||||
@@ -53,6 +53,8 @@ export default async function Page({ searchParams }: PageProps) {
|
|||||||
period: selectedPeriod,
|
period: selectedPeriod,
|
||||||
filters: searchFilters,
|
filters: searchFilters,
|
||||||
slugMaps,
|
slugMaps,
|
||||||
|
hideAnticipatedInstallments:
|
||||||
|
userPreferences?.hideAnticipatedInstallments ?? false,
|
||||||
});
|
});
|
||||||
|
|
||||||
const [transactionsPage, estabelecimentos] = await Promise.all([
|
const [transactionsPage, estabelecimentos] = await Promise.all([
|
||||||
@@ -112,6 +114,9 @@ export default async function Page({ searchParams }: PageProps) {
|
|||||||
}}
|
}}
|
||||||
noteAsColumn={userPreferences?.statementNoteAsColumn ?? false}
|
noteAsColumn={userPreferences?.statementNoteAsColumn ?? false}
|
||||||
columnOrder={userPreferences?.transactionsColumnOrder ?? null}
|
columnOrder={userPreferences?.transactionsColumnOrder ?? null}
|
||||||
|
groupTransactionsByDate={
|
||||||
|
userPreferences?.groupTransactionsByDate ?? true
|
||||||
|
}
|
||||||
attachmentMaxSizeMb={userPreferences?.attachmentMaxSizeMb ?? 50}
|
attachmentMaxSizeMb={userPreferences?.attachmentMaxSizeMb ?? 50}
|
||||||
/>
|
/>
|
||||||
</LogoPrefetchProvider>
|
</LogoPrefetchProvider>
|
||||||
|
|||||||
@@ -4,11 +4,10 @@ import {
|
|||||||
RiShieldCheckLine,
|
RiShieldCheckLine,
|
||||||
RiSmartphoneLine,
|
RiSmartphoneLine,
|
||||||
} from "@remixicon/react";
|
} from "@remixicon/react";
|
||||||
import { headers } from "next/headers";
|
|
||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { AnimateOnScroll } from "@/features/landing/components/animate-on-scroll";
|
import { AnimateOnScroll } from "@/features/landing/components/animate-on-scroll";
|
||||||
import { MobileNav } from "@/features/landing/components/mobile-nav";
|
import { LandingNavbar } from "@/features/landing/components/landing-navbar";
|
||||||
import { SetupTabs } from "@/features/landing/components/setup-tabs";
|
import { SetupTabs } from "@/features/landing/components/setup-tabs";
|
||||||
import {
|
import {
|
||||||
companionBanks,
|
companionBanks,
|
||||||
@@ -16,98 +15,31 @@ import {
|
|||||||
extraFeatures,
|
extraFeatures,
|
||||||
getMetricsItems,
|
getMetricsItems,
|
||||||
mainFeatures,
|
mainFeatures,
|
||||||
navLinks,
|
|
||||||
pwaHighlights,
|
pwaHighlights,
|
||||||
stackItems,
|
stackItems,
|
||||||
whoIsItForItems,
|
whoIsItForItems,
|
||||||
} from "@/features/landing/constants";
|
} from "@/features/landing/constants";
|
||||||
import { landingImages } from "@/features/landing/images";
|
import { landingImages } from "@/features/landing/images";
|
||||||
import { fetchGitHubStats } from "@/features/landing/queries";
|
import {
|
||||||
import { AnimatedThemeToggler } from "@/shared/components/animated-theme-toggler";
|
fetchGitHubStats,
|
||||||
|
getLandingCopyrightYear,
|
||||||
|
} from "@/features/landing/queries";
|
||||||
import { Logo } from "@/shared/components/brand/logo";
|
import { Logo } from "@/shared/components/brand/logo";
|
||||||
import { NavbarShell } from "@/shared/components/navigation/navbar/navbar-shell";
|
|
||||||
import { Badge } from "@/shared/components/ui/badge";
|
import { Badge } from "@/shared/components/ui/badge";
|
||||||
import { Button } from "@/shared/components/ui/button";
|
import { Button } from "@/shared/components/ui/button";
|
||||||
import { Card, CardContent } from "@/shared/components/ui/card";
|
import { Card, CardContent } from "@/shared/components/ui/card";
|
||||||
import { getOptionalUserSession } from "@/shared/lib/auth/server";
|
|
||||||
import { isSignupDisabled } from "@/shared/lib/auth/signup";
|
|
||||||
|
|
||||||
export default async function Page() {
|
export default async function Page() {
|
||||||
const [session, headersList, githubStats] = await Promise.all([
|
const [githubStats, copyrightYear] = await Promise.all([
|
||||||
getOptionalUserSession(),
|
|
||||||
headers(),
|
|
||||||
fetchGitHubStats(),
|
fetchGitHubStats(),
|
||||||
|
getLandingCopyrightYear(),
|
||||||
]);
|
]);
|
||||||
const hostname = headersList.get("host")?.replace(/:\d+$/, "");
|
|
||||||
const publicDomain = process.env.PUBLIC_DOMAIN?.replace(
|
|
||||||
/^https?:\/\//,
|
|
||||||
"",
|
|
||||||
).replace(/:\d+$/, "");
|
|
||||||
const isPublicDomain = !!(publicDomain && hostname === publicDomain);
|
|
||||||
const signupDisabled = isSignupDisabled();
|
|
||||||
const metricsItems = getMetricsItems(githubStats.stars, githubStats.forks);
|
const metricsItems = getMetricsItems(githubStats.stars, githubStats.forks);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex min-h-screen flex-col">
|
<div className="flex min-h-screen flex-col">
|
||||||
{/* Navigation */}
|
{/* Navigation */}
|
||||||
<NavbarShell>
|
<LandingNavbar />
|
||||||
{/* Center Navigation Links */}
|
|
||||||
<nav className="hidden md:flex items-center gap-1 absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2">
|
|
||||||
{navLinks.map(({ href, label }) => (
|
|
||||||
<Link
|
|
||||||
key={href}
|
|
||||||
href={href}
|
|
||||||
className="inline-flex h-9 items-center justify-center rounded-md px-2 text-sm font-medium leading-none text-primary-foreground/75 transition-colors hover:bg-primary-foreground/10 hover:text-primary-foreground dark:text-white/75 dark:hover:bg-white/10 dark:hover:text-white"
|
|
||||||
>
|
|
||||||
{label}
|
|
||||||
</Link>
|
|
||||||
))}
|
|
||||||
</nav>
|
|
||||||
|
|
||||||
<nav className="ml-auto flex items-center gap-1">
|
|
||||||
<AnimatedThemeToggler variant="navbar" />
|
|
||||||
{!isPublicDomain &&
|
|
||||||
(session?.user ? (
|
|
||||||
<Link prefetch href="/dashboard" className="hidden md:block">
|
|
||||||
<Button
|
|
||||||
variant="navbar"
|
|
||||||
size="sm"
|
|
||||||
className="h-9 text-primary-foreground/75 hover:bg-primary-foreground/10 hover:text-primary-foreground shadow-none dark:text-white/75 dark:hover:bg-white/10 dark:hover:text-white"
|
|
||||||
>
|
|
||||||
Dashboard
|
|
||||||
</Button>
|
|
||||||
</Link>
|
|
||||||
) : (
|
|
||||||
<div className="hidden md:flex items-center gap-1">
|
|
||||||
<Link href="/login">
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="sm"
|
|
||||||
className="h-9 text-primary-foreground/75 hover:bg-primary-foreground/10 hover:text-primary-foreground shadow-none dark:text-white/75 dark:hover:bg-white/10 dark:hover:text-white"
|
|
||||||
>
|
|
||||||
Entrar
|
|
||||||
</Button>
|
|
||||||
</Link>
|
|
||||||
{!signupDisabled && (
|
|
||||||
<Link href="/signup">
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="sm"
|
|
||||||
className="h-9 text-primary-foreground/75 hover:bg-primary-foreground/10 hover:text-primary-foreground shadow-none dark:text-white/75 dark:hover:bg-white/10 dark:hover:text-white"
|
|
||||||
>
|
|
||||||
Começar
|
|
||||||
</Button>
|
|
||||||
</Link>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
<MobileNav
|
|
||||||
isPublicDomain={isPublicDomain}
|
|
||||||
isLoggedIn={!!session?.user}
|
|
||||||
signupDisabled={signupDisabled}
|
|
||||||
/>
|
|
||||||
</nav>
|
|
||||||
</NavbarShell>
|
|
||||||
|
|
||||||
{/* Hero Section */}
|
{/* Hero Section */}
|
||||||
<section className="relative overflow-hidden pt-14 md:pt-20 lg:pt-24 pb-0">
|
<section className="relative overflow-hidden pt-14 md:pt-20 lg:pt-24 pb-0">
|
||||||
@@ -698,8 +630,7 @@ export default async function Page() {
|
|||||||
|
|
||||||
<div className="border-t mt-8 md:mt-12 pt-6 md:pt-8 flex flex-col md:flex-row justify-between items-center gap-3 md:gap-4 text-sm text-muted-foreground">
|
<div className="border-t mt-8 md:mt-12 pt-6 md:pt-8 flex flex-col md:flex-row justify-between items-center gap-3 md:gap-4 text-sm text-muted-foreground">
|
||||||
<p>
|
<p>
|
||||||
© {new Date().getFullYear()} openmonetis. Projeto open source
|
© {copyrightYear} openmonetis. Projeto open source sob licença.
|
||||||
sob licença.
|
|
||||||
</p>
|
</p>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<RiShieldCheckLine className="size-4 text-primary" />
|
<RiShieldCheckLine className="size-4 text-primary" />
|
||||||
|
|||||||
@@ -157,6 +157,12 @@ export const userPreferences = pgTable("preferencias_usuario", {
|
|||||||
showTransactionSummary: boolean("mostrar_resumo_lancamento")
|
showTransactionSummary: boolean("mostrar_resumo_lancamento")
|
||||||
.notNull()
|
.notNull()
|
||||||
.default(true),
|
.default(true),
|
||||||
|
groupTransactionsByDate: boolean("agrupar_lancamentos_por_data")
|
||||||
|
.notNull()
|
||||||
|
.default(true),
|
||||||
|
hideAnticipatedInstallments: boolean("ocultar_parcelas_antecipadas")
|
||||||
|
.notNull()
|
||||||
|
.default(false),
|
||||||
dashboardWidgets: jsonb("dashboard_widgets").$type<{
|
dashboardWidgets: jsonb("dashboard_widgets").$type<{
|
||||||
order: string[];
|
order: string[];
|
||||||
hidden: string[];
|
hidden: string[];
|
||||||
@@ -676,6 +682,7 @@ export const transactions = pgTable(
|
|||||||
splitGroupId: uuid("split_group_id"),
|
splitGroupId: uuid("split_group_id"),
|
||||||
transferId: uuid("transfer_id"),
|
transferId: uuid("transfer_id"),
|
||||||
ofxFitId: text("ofx_fit_id"),
|
ofxFitId: text("ofx_fit_id"),
|
||||||
|
ofxImportFingerprint: text("ofx_import_fingerprint"),
|
||||||
importBatchId: text("import_batch_id"),
|
importBatchId: text("import_batch_id"),
|
||||||
},
|
},
|
||||||
(table) => ({
|
(table) => ({
|
||||||
@@ -729,10 +736,12 @@ export const transactions = pgTable(
|
|||||||
anticipationIdIdx: index("lancamentos_antecipacao_id_idx").on(
|
anticipationIdIdx: index("lancamentos_antecipacao_id_idx").on(
|
||||||
table.anticipationId,
|
table.anticipationId,
|
||||||
),
|
),
|
||||||
// Dedup OFX: garante FITID único por usuário
|
// Dedup OFX: identifica a transação completa sem assumir FITID único
|
||||||
ofxFitIdUserIdIdx: uniqueIndex("lancamentos_ofx_fit_id_user_id_idx")
|
ofxImportFingerprintUserIdIdx: uniqueIndex(
|
||||||
.on(table.userId, table.ofxFitId)
|
"lancamentos_ofx_import_fingerprint_user_id_idx",
|
||||||
.where(sql`ofx_fit_id IS NOT NULL`),
|
)
|
||||||
|
.on(table.userId, table.ofxImportFingerprint)
|
||||||
|
.where(sql`ofx_import_fingerprint IS NOT NULL`),
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -36,6 +36,7 @@ export async function fetchCategoryDetails(
|
|||||||
userId: string,
|
userId: string,
|
||||||
categoryId: string,
|
categoryId: string,
|
||||||
period: string,
|
period: string,
|
||||||
|
hideAnticipatedInstallments = false,
|
||||||
): Promise<CategoryDetailData | null> {
|
): Promise<CategoryDetailData | null> {
|
||||||
const category = await db.query.categories.findFirst({
|
const category = await db.query.categories.findFirst({
|
||||||
where: and(eq(categories.userId, userId), eq(categories.id, categoryId)),
|
where: and(eq(categories.userId, userId), eq(categories.id, categoryId)),
|
||||||
@@ -63,6 +64,14 @@ export async function fetchCategoryDetails(
|
|||||||
eq(transactions.transactionType, transactionType),
|
eq(transactions.transactionType, transactionType),
|
||||||
eq(transactions.period, period),
|
eq(transactions.period, period),
|
||||||
eq(transactions.payerId, adminPayerId),
|
eq(transactions.payerId, adminPayerId),
|
||||||
|
...(hideAnticipatedInstallments
|
||||||
|
? [
|
||||||
|
or(
|
||||||
|
isNull(transactions.isAnticipated),
|
||||||
|
eq(transactions.isAnticipated, false),
|
||||||
|
),
|
||||||
|
]
|
||||||
|
: []),
|
||||||
...(isInvoiceCategory ? [] : [sanitizedNote]),
|
...(isInvoiceCategory ? [] : [sanitizedNote]),
|
||||||
),
|
),
|
||||||
with: {
|
with: {
|
||||||
|
|||||||
103
src/features/landing/components/landing-navbar.tsx
Normal file
103
src/features/landing/components/landing-navbar.tsx
Normal file
@@ -0,0 +1,103 @@
|
|||||||
|
import { headers } from "next/headers";
|
||||||
|
import Link from "next/link";
|
||||||
|
import { Suspense } from "react";
|
||||||
|
import { AnimatedThemeToggler } from "@/shared/components/animated-theme-toggler";
|
||||||
|
import { NavbarShell } from "@/shared/components/navigation/navbar/navbar-shell";
|
||||||
|
import { Button } from "@/shared/components/ui/button";
|
||||||
|
import { getOptionalUserSession } from "@/shared/lib/auth/server";
|
||||||
|
import { isSignupDisabled } from "@/shared/lib/auth/signup";
|
||||||
|
import { navLinks } from "../constants";
|
||||||
|
import { MobileNav } from "./mobile-nav";
|
||||||
|
|
||||||
|
async function LandingNavbarControls() {
|
||||||
|
const [session, headersList] = await Promise.all([
|
||||||
|
getOptionalUserSession(),
|
||||||
|
headers(),
|
||||||
|
]);
|
||||||
|
const hostname = headersList.get("host")?.replace(/:\d+$/, "");
|
||||||
|
const publicDomain = process.env.PUBLIC_DOMAIN?.replace(
|
||||||
|
/^https?:\/\//,
|
||||||
|
"",
|
||||||
|
).replace(/:\d+$/, "");
|
||||||
|
const isPublicDomain = !!(publicDomain && hostname === publicDomain);
|
||||||
|
const signupDisabled = isSignupDisabled();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{!isPublicDomain &&
|
||||||
|
(session?.user ? (
|
||||||
|
<Link prefetch href="/dashboard" className="hidden md:block">
|
||||||
|
<Button
|
||||||
|
variant="navbar"
|
||||||
|
size="sm"
|
||||||
|
className="h-9 text-primary-foreground/75 hover:bg-primary-foreground/10 hover:text-primary-foreground shadow-none dark:text-white/75 dark:hover:bg-white/10 dark:hover:text-white"
|
||||||
|
>
|
||||||
|
Dashboard
|
||||||
|
</Button>
|
||||||
|
</Link>
|
||||||
|
) : (
|
||||||
|
<div className="hidden md:flex items-center gap-1">
|
||||||
|
<Link href="/login">
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="h-9 text-primary-foreground/75 hover:bg-primary-foreground/10 hover:text-primary-foreground shadow-none dark:text-white/75 dark:hover:bg-white/10 dark:hover:text-white"
|
||||||
|
>
|
||||||
|
Entrar
|
||||||
|
</Button>
|
||||||
|
</Link>
|
||||||
|
{!signupDisabled && (
|
||||||
|
<Link href="/signup">
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="h-9 text-primary-foreground/75 hover:bg-primary-foreground/10 hover:text-primary-foreground shadow-none dark:text-white/75 dark:hover:bg-white/10 dark:hover:text-white"
|
||||||
|
>
|
||||||
|
Começar
|
||||||
|
</Button>
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<MobileNav
|
||||||
|
isPublicDomain={isPublicDomain}
|
||||||
|
isLoggedIn={!!session?.user}
|
||||||
|
signupDisabled={signupDisabled}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function LandingNavbarControlsFallback() {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div className="hidden h-9 w-36 md:block" aria-hidden="true" />
|
||||||
|
<MobileNav isPublicDomain isLoggedIn={false} signupDisabled />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function LandingNavbar() {
|
||||||
|
return (
|
||||||
|
<NavbarShell>
|
||||||
|
<nav className="hidden md:flex items-center gap-1 absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2">
|
||||||
|
{navLinks.map(({ href, label }) => (
|
||||||
|
<Link
|
||||||
|
key={href}
|
||||||
|
href={href}
|
||||||
|
className="inline-flex h-9 items-center justify-center rounded-md px-2 text-sm font-medium leading-none text-primary-foreground/75 transition-colors hover:bg-primary-foreground/10 hover:text-primary-foreground dark:text-white/75 dark:hover:bg-white/10 dark:hover:text-white"
|
||||||
|
>
|
||||||
|
{label}
|
||||||
|
</Link>
|
||||||
|
))}
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<nav className="ml-auto flex items-center gap-1">
|
||||||
|
<AnimatedThemeToggler variant="navbar" />
|
||||||
|
<Suspense fallback={<LandingNavbarControlsFallback />}>
|
||||||
|
<LandingNavbarControls />
|
||||||
|
</Suspense>
|
||||||
|
</nav>
|
||||||
|
</NavbarShell>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,11 +1,22 @@
|
|||||||
|
import { cacheLife } from "next/cache";
|
||||||
|
|
||||||
|
export async function getLandingCopyrightYear(): Promise<number> {
|
||||||
|
"use cache";
|
||||||
|
cacheLife({ revalidate: 86_400 });
|
||||||
|
|
||||||
|
return new Date().getFullYear();
|
||||||
|
}
|
||||||
|
|
||||||
export async function fetchGitHubStats(): Promise<{
|
export async function fetchGitHubStats(): Promise<{
|
||||||
stars: number;
|
stars: number;
|
||||||
forks: number;
|
forks: number;
|
||||||
}> {
|
}> {
|
||||||
|
"use cache";
|
||||||
|
cacheLife({ revalidate: 3600 });
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch(
|
const res = await fetch(
|
||||||
"https://api.github.com/repos/felipegcoutinho/openmonetis",
|
"https://api.github.com/repos/felipegcoutinho/openmonetis",
|
||||||
{ next: { revalidate: 3600 } },
|
|
||||||
);
|
);
|
||||||
if (!res.ok) return { stars: 200, forks: 60 };
|
if (!res.ok) return { stars: 200, forks: 60 };
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
|
|||||||
@@ -228,6 +228,7 @@ export function CategoryReportFilters({
|
|||||||
<Popover open={startMonthOpen} onOpenChange={setStartMonthOpen}>
|
<Popover open={startMonthOpen} onOpenChange={setStartMonthOpen}>
|
||||||
<PopoverTrigger asChild>
|
<PopoverTrigger asChild>
|
||||||
<Button
|
<Button
|
||||||
|
type="button"
|
||||||
variant="outline"
|
variant="outline"
|
||||||
className="w-[calc(50%-0.25rem)] md:w-[150px] justify-start text-sm border-dashed"
|
className="w-[calc(50%-0.25rem)] md:w-[150px] justify-start text-sm border-dashed"
|
||||||
disabled={isLoading}
|
disabled={isLoading}
|
||||||
@@ -248,6 +249,7 @@ export function CategoryReportFilters({
|
|||||||
<Popover open={endMonthOpen} onOpenChange={setEndMonthOpen}>
|
<Popover open={endMonthOpen} onOpenChange={setEndMonthOpen}>
|
||||||
<PopoverTrigger asChild>
|
<PopoverTrigger asChild>
|
||||||
<Button
|
<Button
|
||||||
|
type="button"
|
||||||
variant="outline"
|
variant="outline"
|
||||||
className="w-[calc(50%-0.25rem)] md:w-[150px] justify-start text-sm border-dashed"
|
className="w-[calc(50%-0.25rem)] md:w-[150px] justify-start text-sm border-dashed"
|
||||||
disabled={isLoading}
|
disabled={isLoading}
|
||||||
|
|||||||
@@ -69,6 +69,8 @@ const updatePreferencesSchema = z.object({
|
|||||||
transactionsColumnOrder: z.array(z.string()).nullable(),
|
transactionsColumnOrder: z.array(z.string()).nullable(),
|
||||||
attachmentMaxSizeMb: z.number().int().min(1).max(100),
|
attachmentMaxSizeMb: z.number().int().min(1).max(100),
|
||||||
showTransactionSummary: z.boolean(),
|
showTransactionSummary: z.boolean(),
|
||||||
|
groupTransactionsByDate: z.boolean(),
|
||||||
|
hideAnticipatedInstallments: z.boolean(),
|
||||||
});
|
});
|
||||||
|
|
||||||
type ResettableUser = {
|
type ResettableUser = {
|
||||||
@@ -584,6 +586,8 @@ export async function updatePreferencesAction(
|
|||||||
transactionsColumnOrder: validated.transactionsColumnOrder,
|
transactionsColumnOrder: validated.transactionsColumnOrder,
|
||||||
attachmentMaxSizeMb: validated.attachmentMaxSizeMb,
|
attachmentMaxSizeMb: validated.attachmentMaxSizeMb,
|
||||||
showTransactionSummary: validated.showTransactionSummary,
|
showTransactionSummary: validated.showTransactionSummary,
|
||||||
|
groupTransactionsByDate: validated.groupTransactionsByDate,
|
||||||
|
hideAnticipatedInstallments: validated.hideAnticipatedInstallments,
|
||||||
updatedAt: new Date(),
|
updatedAt: new Date(),
|
||||||
})
|
})
|
||||||
.where(eq(schema.userPreferences.userId, session.user.id));
|
.where(eq(schema.userPreferences.userId, session.user.id));
|
||||||
@@ -595,6 +599,8 @@ export async function updatePreferencesAction(
|
|||||||
transactionsColumnOrder: validated.transactionsColumnOrder,
|
transactionsColumnOrder: validated.transactionsColumnOrder,
|
||||||
attachmentMaxSizeMb: validated.attachmentMaxSizeMb,
|
attachmentMaxSizeMb: validated.attachmentMaxSizeMb,
|
||||||
showTransactionSummary: validated.showTransactionSummary,
|
showTransactionSummary: validated.showTransactionSummary,
|
||||||
|
groupTransactionsByDate: validated.groupTransactionsByDate,
|
||||||
|
hideAnticipatedInstallments: validated.hideAnticipatedInstallments,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -43,6 +43,8 @@ interface PreferencesFormProps {
|
|||||||
transactionsColumnOrder: string[] | null;
|
transactionsColumnOrder: string[] | null;
|
||||||
attachmentMaxSizeMb: number;
|
attachmentMaxSizeMb: number;
|
||||||
showTransactionSummary: boolean;
|
showTransactionSummary: boolean;
|
||||||
|
groupTransactionsByDate: boolean;
|
||||||
|
hideAnticipatedInstallments: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
function SortableColumnItem({ id }: { id: string }) {
|
function SortableColumnItem({ id }: { id: string }) {
|
||||||
@@ -87,6 +89,8 @@ export function PreferencesForm({
|
|||||||
transactionsColumnOrder: initialColumnOrder,
|
transactionsColumnOrder: initialColumnOrder,
|
||||||
attachmentMaxSizeMb: initialAttachmentMaxSizeMb,
|
attachmentMaxSizeMb: initialAttachmentMaxSizeMb,
|
||||||
showTransactionSummary: initialShowTransactionSummary,
|
showTransactionSummary: initialShowTransactionSummary,
|
||||||
|
groupTransactionsByDate: initialGroupTransactionsByDate,
|
||||||
|
hideAnticipatedInstallments: initialHideAnticipatedInstallments,
|
||||||
}: PreferencesFormProps) {
|
}: PreferencesFormProps) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [isPending, startTransition] = useTransition();
|
const [isPending, startTransition] = useTransition();
|
||||||
@@ -109,6 +113,11 @@ export function PreferencesForm({
|
|||||||
const [showTransactionSummary, setShowTransactionSummary] = useState(
|
const [showTransactionSummary, setShowTransactionSummary] = useState(
|
||||||
initialShowTransactionSummary,
|
initialShowTransactionSummary,
|
||||||
);
|
);
|
||||||
|
const [groupTransactionsByDate, setGroupTransactionsByDate] = useState(
|
||||||
|
initialGroupTransactionsByDate,
|
||||||
|
);
|
||||||
|
const [hideAnticipatedInstallments, setHideAnticipatedInstallments] =
|
||||||
|
useState(initialHideAnticipatedInstallments);
|
||||||
|
|
||||||
const sensors = useSensors(
|
const sensors = useSensors(
|
||||||
useSensor(PointerSensor, { activationConstraint: { distance: 8 } }),
|
useSensor(PointerSensor, { activationConstraint: { distance: 8 } }),
|
||||||
@@ -135,6 +144,8 @@ export function PreferencesForm({
|
|||||||
transactionsColumnOrder: columnOrder,
|
transactionsColumnOrder: columnOrder,
|
||||||
attachmentMaxSizeMb,
|
attachmentMaxSizeMb,
|
||||||
showTransactionSummary,
|
showTransactionSummary,
|
||||||
|
groupTransactionsByDate,
|
||||||
|
hideAnticipatedInstallments,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
@@ -198,6 +209,46 @@ export function PreferencesForm({
|
|||||||
|
|
||||||
<Separator />
|
<Separator />
|
||||||
|
|
||||||
|
<section className="flex items-center justify-between max-w-md gap-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="group-transactions-by-date" className="text-sm">
|
||||||
|
Agrupar por data
|
||||||
|
</Label>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
Mostra uma barra de data acima dos lançamentos daquele dia. Quando
|
||||||
|
desativado, a data volta a aparecer em cada lançamento.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Switch
|
||||||
|
id="group-transactions-by-date"
|
||||||
|
checked={groupTransactionsByDate}
|
||||||
|
onCheckedChange={setGroupTransactionsByDate}
|
||||||
|
disabled={isPending}
|
||||||
|
/>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<Separator />
|
||||||
|
|
||||||
|
<section className="flex items-center justify-between max-w-md gap-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="hide-anticipated-installments" className="text-sm">
|
||||||
|
Ocultar parcelas antecipadas
|
||||||
|
</Label>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
Quando ativo, parcelas já antecipadas não aparecem na tabela de
|
||||||
|
lançamentos.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Switch
|
||||||
|
id="hide-anticipated-installments"
|
||||||
|
checked={hideAnticipatedInstallments}
|
||||||
|
onCheckedChange={setHideAnticipatedInstallments}
|
||||||
|
disabled={isPending}
|
||||||
|
/>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<Separator />
|
||||||
|
|
||||||
<section className="space-y-2 max-w-md">
|
<section className="space-y-2 max-w-md">
|
||||||
<Label className="text-sm">Ordem das colunas</Label>
|
<Label className="text-sm">Ordem das colunas</Label>
|
||||||
<p className="text-sm text-muted-foreground">
|
<p className="text-sm text-muted-foreground">
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ interface UserPreferences {
|
|||||||
transactionsColumnOrder: string[] | null;
|
transactionsColumnOrder: string[] | null;
|
||||||
attachmentMaxSizeMb: number;
|
attachmentMaxSizeMb: number;
|
||||||
showTransactionSummary: boolean;
|
showTransactionSummary: boolean;
|
||||||
|
groupTransactionsByDate: boolean;
|
||||||
|
hideAnticipatedInstallments: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface ApiToken {
|
interface ApiToken {
|
||||||
@@ -36,6 +38,9 @@ export async function fetchUserPreferences(
|
|||||||
transactionsColumnOrder: schema.userPreferences.transactionsColumnOrder,
|
transactionsColumnOrder: schema.userPreferences.transactionsColumnOrder,
|
||||||
attachmentMaxSizeMb: schema.userPreferences.attachmentMaxSizeMb,
|
attachmentMaxSizeMb: schema.userPreferences.attachmentMaxSizeMb,
|
||||||
showTransactionSummary: schema.userPreferences.showTransactionSummary,
|
showTransactionSummary: schema.userPreferences.showTransactionSummary,
|
||||||
|
groupTransactionsByDate: schema.userPreferences.groupTransactionsByDate,
|
||||||
|
hideAnticipatedInstallments:
|
||||||
|
schema.userPreferences.hideAnticipatedInstallments,
|
||||||
})
|
})
|
||||||
.from(schema.userPreferences)
|
.from(schema.userPreferences)
|
||||||
.where(eq(schema.userPreferences.userId, userId))
|
.where(eq(schema.userPreferences.userId, userId))
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { fetchAccountTransactions } from "@/features/accounts/statement-queries";
|
import { fetchAccountTransactions } from "@/features/accounts/statement-queries";
|
||||||
|
import { fetchUserPreferences } from "@/features/settings/queries";
|
||||||
import type { TransactionsExportContext } from "@/features/transactions/lib/export-types";
|
import type { TransactionsExportContext } from "@/features/transactions/lib/export-types";
|
||||||
import {
|
import {
|
||||||
buildSluggedFilters,
|
buildSluggedFilters,
|
||||||
@@ -60,7 +61,10 @@ export async function exportTransactionsDataAction(
|
|||||||
try {
|
try {
|
||||||
const userId = await getUserId();
|
const userId = await getUserId();
|
||||||
const validated = exportTransactionsSchema.parse(input);
|
const validated = exportTransactionsSchema.parse(input);
|
||||||
const filterSources = await fetchTransactionFilterSources(userId);
|
const [filterSources, userPreferences] = await Promise.all([
|
||||||
|
fetchTransactionFilterSources(userId),
|
||||||
|
fetchUserPreferences(userId),
|
||||||
|
]);
|
||||||
const sluggedFilters = buildSluggedFilters(filterSources);
|
const sluggedFilters = buildSluggedFilters(filterSources);
|
||||||
const slugMaps = buildSlugMaps(sluggedFilters);
|
const slugMaps = buildSlugMaps(sluggedFilters);
|
||||||
|
|
||||||
@@ -72,6 +76,8 @@ export async function exportTransactionsDataAction(
|
|||||||
accountId: validated.accountId ?? undefined,
|
accountId: validated.accountId ?? undefined,
|
||||||
cardId: validated.cardId ?? undefined,
|
cardId: validated.cardId ?? undefined,
|
||||||
payerId: validated.payerId ?? undefined,
|
payerId: validated.payerId ?? undefined,
|
||||||
|
hideAnticipatedInstallments:
|
||||||
|
userPreferences?.hideAnticipatedInstallments ?? false,
|
||||||
});
|
});
|
||||||
|
|
||||||
const rows =
|
const rows =
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
"use server";
|
"use server";
|
||||||
|
|
||||||
import { and, eq, inArray } from "drizzle-orm";
|
import { and, eq, inArray, isNull, sql } from "drizzle-orm";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { transactions } from "@/db/schema";
|
import { transactions } from "@/db/schema";
|
||||||
import {
|
import {
|
||||||
@@ -9,23 +9,49 @@ import {
|
|||||||
validateCartaoOwnership,
|
validateCartaoOwnership,
|
||||||
validateContaOwnership,
|
validateContaOwnership,
|
||||||
} from "@/features/transactions/actions/core";
|
} from "@/features/transactions/actions/core";
|
||||||
|
import { createOfxImportFingerprint } from "@/features/transactions/lib/ofx-import-fingerprint";
|
||||||
import { revalidateForEntity } from "@/shared/lib/actions/helpers";
|
import { revalidateForEntity } from "@/shared/lib/actions/helpers";
|
||||||
import { getUserId } from "@/shared/lib/auth/server";
|
import { getUserId } from "@/shared/lib/auth/server";
|
||||||
import { db } from "@/shared/lib/db";
|
import { db } from "@/shared/lib/db";
|
||||||
|
import {
|
||||||
|
normalizeOfxIdentityText,
|
||||||
|
type OfxIdentityRow,
|
||||||
|
type OfxImportDestination,
|
||||||
|
} from "@/shared/lib/import/ofx-identity";
|
||||||
import { uuidSchema } from "@/shared/lib/schemas/common";
|
import { uuidSchema } from "@/shared/lib/schemas/common";
|
||||||
import { parseLocalDateString } from "@/shared/utils/date";
|
import { formatDecimalForDbRequired } from "@/shared/utils/currency";
|
||||||
|
import { parseLocalDateString, toDateOnlyString } from "@/shared/utils/date";
|
||||||
|
|
||||||
const importRowSchema = z.object({
|
const ofxIdentityRowSchema = z.object({
|
||||||
externalId: z.string().nullable(),
|
externalId: z.string().nullable(),
|
||||||
|
externalIdOccurrence: z.number().int().nonnegative(),
|
||||||
date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Data inválida."),
|
date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Data inválida."),
|
||||||
amount: z.number().positive(),
|
amount: z.number().positive(),
|
||||||
description: z.string().min(1, "Descrição obrigatória."),
|
|
||||||
transactionType: z.enum(["income", "expense"]),
|
transactionType: z.enum(["income", "expense"]),
|
||||||
|
sourceDescription: z.string(),
|
||||||
|
});
|
||||||
|
|
||||||
|
const ofxImportDestinationSchema = z.discriminatedUnion("type", [
|
||||||
|
z.object({ type: z.literal("account"), id: uuidSchema("Conta") }),
|
||||||
|
z.object({ type: z.literal("card"), id: uuidSchema("Cartão") }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const duplicateCheckSchema = z.object({
|
||||||
|
source: z.string().min(1),
|
||||||
|
accountNumber: z.string().nullable(),
|
||||||
|
destination: ofxImportDestinationSchema,
|
||||||
|
rows: z.array(ofxIdentityRowSchema),
|
||||||
|
});
|
||||||
|
|
||||||
|
const importRowSchema = ofxIdentityRowSchema.extend({
|
||||||
|
description: z.string().min(1, "Descrição obrigatória."),
|
||||||
categoryId: uuidSchema("Category").nullable().optional(),
|
categoryId: uuidSchema("Category").nullable().optional(),
|
||||||
payerId: uuidSchema("Payer").nullable().optional(),
|
payerId: uuidSchema("Payer").nullable().optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
const importSchema = z.object({
|
const importSchema = z.object({
|
||||||
|
source: z.string().min(1),
|
||||||
|
accountNumber: z.string().nullable(),
|
||||||
rows: z.array(importRowSchema).min(1, "Selecione ao menos uma transação."),
|
rows: z.array(importRowSchema).min(1, "Selecione ao menos uma transação."),
|
||||||
payerId: uuidSchema("Payer").nullable().optional(),
|
payerId: uuidSchema("Payer").nullable().optional(),
|
||||||
accountId: uuidSchema("FinancialAccount").nullable().optional(),
|
accountId: uuidSchema("FinancialAccount").nullable().optional(),
|
||||||
@@ -44,22 +70,197 @@ type ImportResult =
|
|||||||
| { success: true; imported: number; skipped: number; importBatchId: string }
|
| { success: true; imported: number; skipped: number; importBatchId: string }
|
||||||
| { success: false; error: string };
|
| { success: false; error: string };
|
||||||
|
|
||||||
// Retorna os externalIds que já existem para o usuário (para marcar duplicatas)
|
type ImportMatch = {
|
||||||
export async function checkDuplicateFitIds(
|
fingerprint: string | null;
|
||||||
fitIds: string[],
|
existingTransactionId: string | null;
|
||||||
): Promise<string[]> {
|
};
|
||||||
const userId = await getUserId();
|
|
||||||
const ids = fitIds.filter(Boolean);
|
|
||||||
if (ids.length === 0) return [];
|
|
||||||
|
|
||||||
const rows = await db
|
type LegacyImportCandidate = {
|
||||||
.select({ ofxFitId: transactions.ofxFitId })
|
id: string;
|
||||||
|
name: string;
|
||||||
|
amount: string;
|
||||||
|
purchaseDate: Date;
|
||||||
|
transactionType: string;
|
||||||
|
ofxFitId: string | null;
|
||||||
|
accountId: string | null;
|
||||||
|
cardId: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
function isDestinationMatch(
|
||||||
|
candidate: LegacyImportCandidate,
|
||||||
|
destination: OfxImportDestination,
|
||||||
|
): boolean {
|
||||||
|
return destination.type === "card"
|
||||||
|
? candidate.cardId === destination.id
|
||||||
|
: candidate.accountId === destination.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isLegacyImportMatch(
|
||||||
|
candidate: LegacyImportCandidate,
|
||||||
|
row: OfxIdentityRow,
|
||||||
|
destination: OfxImportDestination,
|
||||||
|
): boolean {
|
||||||
|
if (
|
||||||
|
!row.externalId ||
|
||||||
|
row.externalIdOccurrence !== 0 ||
|
||||||
|
candidate.ofxFitId !== row.externalId ||
|
||||||
|
!isDestinationMatch(candidate, destination)
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const expectedType = row.transactionType === "income" ? "Receita" : "Despesa";
|
||||||
|
const signedAmount =
|
||||||
|
row.transactionType === "expense" ? -row.amount : row.amount;
|
||||||
|
|
||||||
|
return (
|
||||||
|
toDateOnlyString(candidate.purchaseDate) === row.date &&
|
||||||
|
formatDecimalForDbRequired(Number(candidate.amount)) ===
|
||||||
|
formatDecimalForDbRequired(signedAmount) &&
|
||||||
|
candidate.transactionType === expectedType &&
|
||||||
|
normalizeOfxIdentityText(candidate.name) ===
|
||||||
|
normalizeOfxIdentityText(row.sourceDescription)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function findExistingImports(
|
||||||
|
userId: string,
|
||||||
|
source: string,
|
||||||
|
accountNumber: string | null,
|
||||||
|
destination: OfxImportDestination,
|
||||||
|
rows: OfxIdentityRow[],
|
||||||
|
): Promise<ImportMatch[]> {
|
||||||
|
const fingerprints = rows.map((row) =>
|
||||||
|
createOfxImportFingerprint({
|
||||||
|
source,
|
||||||
|
accountNumber,
|
||||||
|
destination,
|
||||||
|
row,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const fingerprintValues = [
|
||||||
|
...new Set(
|
||||||
|
fingerprints.filter(
|
||||||
|
(fingerprint): fingerprint is string => fingerprint !== null,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
const fitIds = [
|
||||||
|
...new Set(
|
||||||
|
rows
|
||||||
|
.map((row) => row.externalId)
|
||||||
|
.filter((fitId): fitId is string => fitId !== null),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
|
||||||
|
const [fingerprintMatches, legacyCandidates] = await Promise.all([
|
||||||
|
fingerprintValues.length > 0
|
||||||
|
? db
|
||||||
|
.select({
|
||||||
|
id: transactions.id,
|
||||||
|
fingerprint: transactions.ofxImportFingerprint,
|
||||||
|
})
|
||||||
.from(transactions)
|
.from(transactions)
|
||||||
.where(
|
.where(
|
||||||
and(eq(transactions.userId, userId), inArray(transactions.ofxFitId, ids)),
|
and(
|
||||||
|
eq(transactions.userId, userId),
|
||||||
|
inArray(transactions.ofxImportFingerprint, fingerprintValues),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
: Promise.resolve([]),
|
||||||
|
fitIds.length > 0
|
||||||
|
? db
|
||||||
|
.select({
|
||||||
|
id: transactions.id,
|
||||||
|
name: transactions.name,
|
||||||
|
amount: transactions.amount,
|
||||||
|
purchaseDate: transactions.purchaseDate,
|
||||||
|
transactionType: transactions.transactionType,
|
||||||
|
ofxFitId: transactions.ofxFitId,
|
||||||
|
accountId: transactions.accountId,
|
||||||
|
cardId: transactions.cardId,
|
||||||
|
})
|
||||||
|
.from(transactions)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(transactions.userId, userId),
|
||||||
|
isNull(transactions.ofxImportFingerprint),
|
||||||
|
inArray(transactions.ofxFitId, fitIds),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
: Promise.resolve([]),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const transactionIdByFingerprint = new Map(
|
||||||
|
fingerprintMatches.flatMap((match) =>
|
||||||
|
match.fingerprint ? [[match.fingerprint, match.id] as const] : [],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
const consumedLegacyIds = new Set<string>();
|
||||||
|
|
||||||
|
return rows.map((row, index) => {
|
||||||
|
const fingerprint = fingerprints[index] ?? null;
|
||||||
|
const currentTransactionId = fingerprint
|
||||||
|
? (transactionIdByFingerprint.get(fingerprint) ?? null)
|
||||||
|
: null;
|
||||||
|
|
||||||
|
if (currentTransactionId) {
|
||||||
|
return { fingerprint, existingTransactionId: currentTransactionId };
|
||||||
|
}
|
||||||
|
|
||||||
|
const legacyMatch = legacyCandidates.find(
|
||||||
|
(candidate) =>
|
||||||
|
!consumedLegacyIds.has(candidate.id) &&
|
||||||
|
isLegacyImportMatch(candidate, row, destination),
|
||||||
);
|
);
|
||||||
|
|
||||||
return rows.map((r) => r.ofxFitId).filter((id): id is string => id !== null);
|
if (legacyMatch) {
|
||||||
|
consumedLegacyIds.add(legacyMatch.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
fingerprint,
|
||||||
|
existingTransactionId: legacyMatch?.id ?? null,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function validateDestinationOwnership(
|
||||||
|
userId: string,
|
||||||
|
destination: OfxImportDestination,
|
||||||
|
): Promise<boolean> {
|
||||||
|
return destination.type === "card"
|
||||||
|
? validateCartaoOwnership(userId, destination.id)
|
||||||
|
: validateContaOwnership(userId, destination.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function checkDuplicateOfxTransactions(
|
||||||
|
input: unknown,
|
||||||
|
): Promise<
|
||||||
|
{ success: true; rows: ImportMatch[] } | { success: false; error: string }
|
||||||
|
> {
|
||||||
|
const userId = await getUserId();
|
||||||
|
const parsed = duplicateCheckSchema.safeParse(input);
|
||||||
|
|
||||||
|
if (!parsed.success) {
|
||||||
|
return { success: false, error: "Dados do arquivo inválidos." };
|
||||||
|
}
|
||||||
|
|
||||||
|
const { source, accountNumber, destination, rows } = parsed.data;
|
||||||
|
if (!(await validateDestinationOwnership(userId, destination))) {
|
||||||
|
return { success: false, error: "Conta ou cartão não encontrado." };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
rows: await findExistingImports(
|
||||||
|
userId,
|
||||||
|
source,
|
||||||
|
accountNumber,
|
||||||
|
destination,
|
||||||
|
rows,
|
||||||
|
),
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function importTransactionsAction(
|
export async function importTransactionsAction(
|
||||||
@@ -75,8 +276,25 @@ export async function importTransactionsAction(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const { rows, payerId, accountId, cardId, paymentMethod, invoicePeriod } =
|
const {
|
||||||
parsed.data;
|
source,
|
||||||
|
accountNumber,
|
||||||
|
rows,
|
||||||
|
payerId,
|
||||||
|
accountId,
|
||||||
|
cardId,
|
||||||
|
paymentMethod,
|
||||||
|
invoicePeriod,
|
||||||
|
} = parsed.data;
|
||||||
|
const destination: OfxImportDestination | null = cardId
|
||||||
|
? { type: "card", id: cardId }
|
||||||
|
: accountId
|
||||||
|
? { type: "account", id: accountId }
|
||||||
|
: null;
|
||||||
|
|
||||||
|
if (!destination || (accountId && cardId)) {
|
||||||
|
return { success: false, error: "Selecione uma conta ou cartão." };
|
||||||
|
}
|
||||||
|
|
||||||
const payerIdsByRow = rows.map((row) => row.payerId ?? payerId ?? null);
|
const payerIdsByRow = rows.map((row) => row.payerId ?? payerId ?? null);
|
||||||
|
|
||||||
@@ -109,8 +327,33 @@ export async function importTransactionsAction(
|
|||||||
if (!accountOk) return { success: false, error: "Conta não encontrada." };
|
if (!accountOk) return { success: false, error: "Conta não encontrada." };
|
||||||
if (!cardOk) return { success: false, error: "Cartão não encontrado." };
|
if (!cardOk) return { success: false, error: "Cartão não encontrado." };
|
||||||
|
|
||||||
if (rows.length === 0) {
|
const importMatches = await findExistingImports(
|
||||||
return { success: true, imported: 0, skipped: 0, importBatchId: "" };
|
userId,
|
||||||
|
source,
|
||||||
|
accountNumber,
|
||||||
|
destination,
|
||||||
|
rows,
|
||||||
|
);
|
||||||
|
const rowsToImport = rows.flatMap((row, index) => {
|
||||||
|
const match = importMatches[index];
|
||||||
|
return match?.existingTransactionId
|
||||||
|
? []
|
||||||
|
: [
|
||||||
|
{
|
||||||
|
row,
|
||||||
|
payerId: payerIdsByRow[index],
|
||||||
|
fingerprint: match?.fingerprint ?? null,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
});
|
||||||
|
|
||||||
|
if (rowsToImport.length === 0) {
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
imported: 0,
|
||||||
|
skipped: rows.length,
|
||||||
|
importBatchId: "",
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const importBatchId = crypto.randomUUID();
|
const importBatchId = crypto.randomUUID();
|
||||||
@@ -118,7 +361,7 @@ export async function importTransactionsAction(
|
|||||||
// Cartão de crédito: fatura pode ainda não ter sido paga
|
// Cartão de crédito: fatura pode ainda não ter sido paga
|
||||||
const isSettled = paymentMethod !== "Cartão de crédito";
|
const isSettled = paymentMethod !== "Cartão de crédito";
|
||||||
|
|
||||||
const records = rows.map((row, index) => {
|
const records = rowsToImport.map(({ row, payerId, fingerprint }) => {
|
||||||
const purchaseDate = parseLocalDateString(row.date);
|
const purchaseDate = parseLocalDateString(row.date);
|
||||||
const period =
|
const period =
|
||||||
invoicePeriod ??
|
invoicePeriod ??
|
||||||
@@ -137,21 +380,24 @@ export async function importTransactionsAction(
|
|||||||
period,
|
period,
|
||||||
isSettled,
|
isSettled,
|
||||||
userId,
|
userId,
|
||||||
payerId: payerIdsByRow[index],
|
payerId,
|
||||||
accountId: accountId ?? null,
|
accountId: accountId ?? null,
|
||||||
cardId: cardId ?? null,
|
cardId: cardId ?? null,
|
||||||
categoryId: row.categoryId ?? null,
|
categoryId: row.categoryId ?? null,
|
||||||
ofxFitId: row.externalId,
|
ofxFitId: row.externalId,
|
||||||
|
ofxImportFingerprint: fingerprint,
|
||||||
importBatchId,
|
importBatchId,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
// onConflictDoNothing usa o uniqueIndex (userId, ofxFitId) WHERE ofxFitId IS NOT NULL
|
// O índice de fingerprint protege contra importações concorrentes do mesmo OFX.
|
||||||
// eliminando o SELECT prévio de checkDuplicateFitIds
|
|
||||||
const inserted = await db
|
const inserted = await db
|
||||||
.insert(transactions)
|
.insert(transactions)
|
||||||
.values(records)
|
.values(records)
|
||||||
.onConflictDoNothing()
|
.onConflictDoNothing({
|
||||||
|
target: [transactions.userId, transactions.ofxImportFingerprint],
|
||||||
|
where: sql`ofx_import_fingerprint IS NOT NULL`,
|
||||||
|
})
|
||||||
.returning({ id: transactions.id });
|
.returning({ id: transactions.id });
|
||||||
|
|
||||||
await revalidateForEntity("transactions", userId);
|
await revalidateForEntity("transactions", userId);
|
||||||
@@ -159,23 +405,31 @@ export async function importTransactionsAction(
|
|||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
imported: inserted.length,
|
imported: inserted.length,
|
||||||
skipped: records.length - inserted.length,
|
skipped: rows.length - inserted.length,
|
||||||
importBatchId,
|
importBatchId,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function deleteTransactionByFitId(
|
export async function deleteImportedTransaction(
|
||||||
fitId: string,
|
transactionId: string,
|
||||||
): Promise<{ success: boolean; error?: string }> {
|
): Promise<{ success: boolean; error?: string }> {
|
||||||
if (!fitId) return { success: false, error: "FITID inválido." };
|
const parsedId = uuidSchema("Lançamento").safeParse(transactionId);
|
||||||
|
if (!parsedId.success) {
|
||||||
|
return { success: false, error: "Lançamento inválido." };
|
||||||
|
}
|
||||||
|
|
||||||
const userId = await getUserId();
|
const userId = await getUserId();
|
||||||
|
|
||||||
await db
|
const deleted = await db
|
||||||
.delete(transactions)
|
.delete(transactions)
|
||||||
.where(
|
.where(
|
||||||
and(eq(transactions.userId, userId), eq(transactions.ofxFitId, fitId)),
|
and(eq(transactions.userId, userId), eq(transactions.id, parsedId.data)),
|
||||||
);
|
)
|
||||||
|
.returning({ id: transactions.id });
|
||||||
|
|
||||||
|
if (deleted.length === 0) {
|
||||||
|
return { success: false, error: "Lançamento não encontrado." };
|
||||||
|
}
|
||||||
|
|
||||||
await revalidateForEntity("transactions", userId);
|
await revalidateForEntity("transactions", userId);
|
||||||
|
|
||||||
|
|||||||
@@ -72,7 +72,7 @@ function InlinePeriodPicker({
|
|||||||
return (
|
return (
|
||||||
<div className="-mt-1">
|
<div className="-mt-1">
|
||||||
<span className="text-xs text-muted-foreground">Fatura de </span>
|
<span className="text-xs text-muted-foreground">Fatura de </span>
|
||||||
<Popover open={open} onOpenChange={setOpen}>
|
<Popover modal open={open} onOpenChange={setOpen}>
|
||||||
<PopoverTrigger asChild>
|
<PopoverTrigger asChild>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ function InlinePeriodPicker({
|
|||||||
return (
|
return (
|
||||||
<div className="ml-1">
|
<div className="ml-1">
|
||||||
<span className="text-xs text-muted-foreground">Fatura de </span>
|
<span className="text-xs text-muted-foreground">Fatura de </span>
|
||||||
<Popover open={open} onOpenChange={setOpen}>
|
<Popover modal open={open} onOpenChange={setOpen}>
|
||||||
<PopoverTrigger asChild>
|
<PopoverTrigger asChild>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
|
|||||||
@@ -1,21 +1,15 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import {
|
import { useCallback, useMemo, useRef, useState, useTransition } from "react";
|
||||||
useCallback,
|
|
||||||
useEffect,
|
|
||||||
useMemo,
|
|
||||||
useState,
|
|
||||||
useTransition,
|
|
||||||
} from "react";
|
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import {
|
import {
|
||||||
fetchCategoryMappings,
|
fetchCategoryMappings,
|
||||||
saveCategoryMappings,
|
saveCategoryMappings,
|
||||||
} from "@/features/transactions/actions/category-memory-action";
|
} from "@/features/transactions/actions/category-memory-action";
|
||||||
import {
|
import {
|
||||||
checkDuplicateFitIds,
|
checkDuplicateOfxTransactions,
|
||||||
deleteTransactionByFitId,
|
deleteImportedTransaction,
|
||||||
importTransactionsAction,
|
importTransactionsAction,
|
||||||
undoImportAction,
|
undoImportAction,
|
||||||
} from "@/features/transactions/actions/import-action";
|
} from "@/features/transactions/actions/import-action";
|
||||||
@@ -43,6 +37,7 @@ import {
|
|||||||
} from "@/shared/components/ui/card";
|
} from "@/shared/components/ui/card";
|
||||||
import { Skeleton } from "@/shared/components/ui/skeleton";
|
import { Skeleton } from "@/shared/components/ui/skeleton";
|
||||||
import type { ImportStatement } from "@/shared/lib/import/types";
|
import type { ImportStatement } from "@/shared/lib/import/types";
|
||||||
|
import { createClientSafeId } from "@/shared/utils/id";
|
||||||
|
|
||||||
const categoryGroupByTransactionType = {
|
const categoryGroupByTransactionType = {
|
||||||
expense: "despesa",
|
expense: "despesa",
|
||||||
@@ -69,6 +64,7 @@ export function ImportPage({
|
|||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [isPending, startTransition] = useTransition();
|
const [isPending, startTransition] = useTransition();
|
||||||
const [isChecking, setIsChecking] = useState(false);
|
const [isChecking, setIsChecking] = useState(false);
|
||||||
|
const duplicateCheckRequestId = useRef(0);
|
||||||
|
|
||||||
const [statement, setStatement] = useState<ImportStatement | null>(null);
|
const [statement, setStatement] = useState<ImportStatement | null>(null);
|
||||||
const [rows, setRows] = useState<ReviewRow[]>([]);
|
const [rows, setRows] = useState<ReviewRow[]>([]);
|
||||||
@@ -95,23 +91,45 @@ export function ImportPage({
|
|||||||
|
|
||||||
const handleParsed = useCallback(
|
const handleParsed = useCallback(
|
||||||
async (stmt: ImportStatement) => {
|
async (stmt: ImportStatement) => {
|
||||||
|
const requestId = ++duplicateCheckRequestId.current;
|
||||||
setStatement(stmt);
|
setStatement(stmt);
|
||||||
setIsChecking(true);
|
setIsChecking(true);
|
||||||
|
const defaultAccountCardValue = stmt.isCreditCard
|
||||||
|
? cardOptions[0]
|
||||||
|
? encodeAccountCard("card", cardOptions[0].value)
|
||||||
|
: null
|
||||||
|
: accountOptions[0]
|
||||||
|
? encodeAccountCard("account", accountOptions[0].value)
|
||||||
|
: null;
|
||||||
|
const destination = defaultAccountCardValue
|
||||||
|
? decodeAccountCard(defaultAccountCardValue)
|
||||||
|
: null;
|
||||||
|
setAccountCardValue(defaultAccountCardValue);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const fitIds = stmt.transactions
|
const [duplicateResult, categoryMappings] = await Promise.all([
|
||||||
.map((t) => t.externalId)
|
destination
|
||||||
.filter((id): id is string => id !== null);
|
? checkDuplicateOfxTransactions({
|
||||||
|
source: stmt.source,
|
||||||
const [duplicates, categoryMappings] = await Promise.all([
|
accountNumber: stmt.accountNumber,
|
||||||
checkDuplicateFitIds(fitIds).then((ids) => new Set(ids)),
|
destination,
|
||||||
|
rows: stmt.transactions,
|
||||||
|
})
|
||||||
|
: Promise.resolve({ success: true as const, rows: [] }),
|
||||||
fetchCategoryMappings(stmt.transactions.map((t) => t.description)),
|
fetchCategoryMappings(stmt.transactions.map((t) => t.description)),
|
||||||
]);
|
]);
|
||||||
|
if (requestId !== duplicateCheckRequestId.current) return;
|
||||||
|
if (!duplicateResult.success) {
|
||||||
|
toast.error(duplicateResult.error);
|
||||||
|
}
|
||||||
|
|
||||||
setRows(
|
setRows(
|
||||||
stmt.transactions.map((t) => {
|
stmt.transactions.map((t, index) => {
|
||||||
let mappedCategoryId =
|
let mappedCategoryId =
|
||||||
categoryMappings[normalizeDescriptionKey(t.description)] ?? null;
|
categoryMappings[normalizeDescriptionKey(t.description)] ?? null;
|
||||||
|
const existingTransactionId = duplicateResult.success
|
||||||
|
? (duplicateResult.rows[index]?.existingTransactionId ?? null)
|
||||||
|
: null;
|
||||||
|
|
||||||
if (t.categoryRaw) {
|
if (t.categoryRaw) {
|
||||||
const categoryRaw = normalizeCategoryName(t.categoryRaw);
|
const categoryRaw = normalizeCategoryName(t.categoryRaw);
|
||||||
@@ -125,8 +143,10 @@ export function ImportPage({
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
...t,
|
...t,
|
||||||
isDuplicate: t.externalId ? duplicates.has(t.externalId) : false,
|
reviewId: createClientSafeId(),
|
||||||
selected: t.externalId ? !duplicates.has(t.externalId) : true,
|
existingTransactionId,
|
||||||
|
isDuplicate: existingTransactionId !== null,
|
||||||
|
selected: existingTransactionId === null,
|
||||||
payerId,
|
payerId,
|
||||||
categoryId: isCategoryCompatible(
|
categoryId: isCategoryCompatible(
|
||||||
mappedCategoryId,
|
mappedCategoryId,
|
||||||
@@ -138,23 +158,64 @@ export function ImportPage({
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
} finally {
|
} finally {
|
||||||
|
if (requestId === duplicateCheckRequestId.current) {
|
||||||
setIsChecking(false);
|
setIsChecking(false);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
},
|
},
|
||||||
[isCategoryCompatible, payerId, categoryOptions],
|
[
|
||||||
|
accountOptions,
|
||||||
|
cardOptions,
|
||||||
|
categoryOptions,
|
||||||
|
isCategoryCompatible,
|
||||||
|
payerId,
|
||||||
|
],
|
||||||
);
|
);
|
||||||
|
|
||||||
// Pré-seleciona cartão ou conta com base no tipo detectado no OFX
|
const handleAccountCardChange = async (value: string | null) => {
|
||||||
useEffect(() => {
|
const requestId = ++duplicateCheckRequestId.current;
|
||||||
if (!statement || accountCardValue) return;
|
setAccountCardValue(value);
|
||||||
if (statement.isCreditCard && cardOptions[0]) {
|
const destination = value ? decodeAccountCard(value) : null;
|
||||||
setAccountCardValue(encodeAccountCard("card", cardOptions[0].value));
|
if (!statement || !destination) {
|
||||||
} else if (!statement.isCreditCard && accountOptions[0]) {
|
setIsChecking(false);
|
||||||
setAccountCardValue(
|
return;
|
||||||
encodeAccountCard("account", accountOptions[0].value),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}, [statement, cardOptions, accountOptions, accountCardValue]);
|
|
||||||
|
setIsChecking(true);
|
||||||
|
try {
|
||||||
|
const result = await checkDuplicateOfxTransactions({
|
||||||
|
source: statement.source,
|
||||||
|
accountNumber: statement.accountNumber,
|
||||||
|
destination,
|
||||||
|
rows,
|
||||||
|
});
|
||||||
|
if (requestId !== duplicateCheckRequestId.current) return;
|
||||||
|
if (!result.success) {
|
||||||
|
toast.error(result.error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setRows((previousRows) =>
|
||||||
|
previousRows.map((row, index) => {
|
||||||
|
const existingTransactionId =
|
||||||
|
result.rows[index]?.existingTransactionId ?? null;
|
||||||
|
const isDuplicate = existingTransactionId !== null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
...row,
|
||||||
|
existingTransactionId,
|
||||||
|
selected:
|
||||||
|
row.isDuplicate === isDuplicate ? row.selected : !isDuplicate,
|
||||||
|
isDuplicate,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
if (requestId === duplicateCheckRequestId.current) {
|
||||||
|
setIsChecking(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const toggleRow = (index: number) => {
|
const toggleRow = (index: number) => {
|
||||||
setRows((prev) =>
|
setRows((prev) =>
|
||||||
@@ -184,9 +245,9 @@ export function ImportPage({
|
|||||||
|
|
||||||
const handleUndoDuplicate = async (index: number) => {
|
const handleUndoDuplicate = async (index: number) => {
|
||||||
const row = rows[index];
|
const row = rows[index];
|
||||||
if (!row?.externalId) return;
|
if (!row?.existingTransactionId) return;
|
||||||
|
|
||||||
const result = await deleteTransactionByFitId(row.externalId);
|
const result = await deleteImportedTransaction(row.existingTransactionId);
|
||||||
if (!result.success) {
|
if (!result.success) {
|
||||||
toast.error("Não foi possível desfazer a importação anterior.");
|
toast.error("Não foi possível desfazer a importação anterior.");
|
||||||
return;
|
return;
|
||||||
@@ -194,7 +255,14 @@ export function ImportPage({
|
|||||||
|
|
||||||
setRows((prev) =>
|
setRows((prev) =>
|
||||||
prev.map((r, i) =>
|
prev.map((r, i) =>
|
||||||
i === index ? { ...r, isDuplicate: false, selected: true } : r,
|
i === index
|
||||||
|
? {
|
||||||
|
...r,
|
||||||
|
existingTransactionId: null,
|
||||||
|
isDuplicate: false,
|
||||||
|
selected: true,
|
||||||
|
}
|
||||||
|
: r,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
toast.success("Importação anterior removida.");
|
toast.success("Importação anterior removida.");
|
||||||
@@ -261,11 +329,15 @@ export function ImportPage({
|
|||||||
|
|
||||||
startTransition(async () => {
|
startTransition(async () => {
|
||||||
const result = await importTransactionsAction({
|
const result = await importTransactionsAction({
|
||||||
|
source: statement.source,
|
||||||
|
accountNumber: statement.accountNumber,
|
||||||
rows: selectedRows.map((r) => ({
|
rows: selectedRows.map((r) => ({
|
||||||
externalId: r.externalId,
|
externalId: r.externalId,
|
||||||
|
externalIdOccurrence: r.externalIdOccurrence,
|
||||||
date: r.date,
|
date: r.date,
|
||||||
amount: r.amount,
|
amount: r.amount,
|
||||||
description: r.description,
|
description: r.description,
|
||||||
|
sourceDescription: r.sourceDescription,
|
||||||
transactionType: r.transactionType,
|
transactionType: r.transactionType,
|
||||||
categoryId: r.categoryId,
|
categoryId: r.categoryId,
|
||||||
payerId: r.payerId,
|
payerId: r.payerId,
|
||||||
@@ -369,7 +441,7 @@ export function ImportPage({
|
|||||||
accountCardValue={accountCardValue}
|
accountCardValue={accountCardValue}
|
||||||
payerId={payerId}
|
payerId={payerId}
|
||||||
invoicePeriod={invoicePeriod}
|
invoicePeriod={invoicePeriod}
|
||||||
onAccountCardChange={setAccountCardValue}
|
onAccountCardChange={handleAccountCardChange}
|
||||||
onPayerChange={handleBulkPayerChange}
|
onPayerChange={handleBulkPayerChange}
|
||||||
onInvoicePeriodChange={setInvoicePeriod}
|
onInvoicePeriodChange={setInvoicePeriod}
|
||||||
onBulkCategoryChange={handleBulkCategoryChange}
|
onBulkCategoryChange={handleBulkCategoryChange}
|
||||||
|
|||||||
@@ -43,8 +43,10 @@ const categoryGroupByTransactionType: Record<
|
|||||||
};
|
};
|
||||||
|
|
||||||
export type ReviewRow = ImportedTransaction & {
|
export type ReviewRow = ImportedTransaction & {
|
||||||
|
reviewId: string;
|
||||||
selected: boolean;
|
selected: boolean;
|
||||||
isDuplicate: boolean;
|
isDuplicate: boolean;
|
||||||
|
existingTransactionId: string | null;
|
||||||
categoryId: string | null;
|
categoryId: string | null;
|
||||||
payerId: string | null;
|
payerId: string | null;
|
||||||
};
|
};
|
||||||
@@ -80,6 +82,7 @@ export function ReviewTable({
|
|||||||
const virtualizer = useVirtualizer({
|
const virtualizer = useVirtualizer({
|
||||||
count: rows.length,
|
count: rows.length,
|
||||||
getScrollElement: () => parentRef.current,
|
getScrollElement: () => parentRef.current,
|
||||||
|
getItemKey: (index) => rows[index]?.reviewId ?? index,
|
||||||
estimateSize: () => 44,
|
estimateSize: () => 44,
|
||||||
overscan: 8,
|
overscan: 8,
|
||||||
});
|
});
|
||||||
@@ -141,7 +144,7 @@ export function ReviewTable({
|
|||||||
);
|
);
|
||||||
return (
|
return (
|
||||||
<TableRow
|
<TableRow
|
||||||
key={row.externalId ?? `${row.date}-${index}`}
|
key={row.reviewId}
|
||||||
className={
|
className={
|
||||||
row.isDuplicate && !row.selected ? "opacity-50" : ""
|
row.isDuplicate && !row.selected ? "opacity-50" : ""
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -82,6 +82,7 @@ interface TransactionsPageProps {
|
|||||||
allowCreate?: boolean;
|
allowCreate?: boolean;
|
||||||
noteAsColumn?: boolean;
|
noteAsColumn?: boolean;
|
||||||
columnOrder?: string[] | null;
|
columnOrder?: string[] | null;
|
||||||
|
groupTransactionsByDate?: boolean;
|
||||||
defaultCardId?: string | null;
|
defaultCardId?: string | null;
|
||||||
defaultPaymentMethod?: string | null;
|
defaultPaymentMethod?: string | null;
|
||||||
lockCardSelection?: boolean;
|
lockCardSelection?: boolean;
|
||||||
@@ -119,6 +120,7 @@ export function TransactionsPage({
|
|||||||
allowCreate = true,
|
allowCreate = true,
|
||||||
noteAsColumn = false,
|
noteAsColumn = false,
|
||||||
columnOrder = null,
|
columnOrder = null,
|
||||||
|
groupTransactionsByDate = true,
|
||||||
defaultCardId,
|
defaultCardId,
|
||||||
defaultPaymentMethod,
|
defaultPaymentMethod,
|
||||||
lockCardSelection,
|
lockCardSelection,
|
||||||
@@ -745,6 +747,7 @@ export function TransactionsPage({
|
|||||||
currentUserId={currentUserId}
|
currentUserId={currentUserId}
|
||||||
noteAsColumn={noteAsColumn}
|
noteAsColumn={noteAsColumn}
|
||||||
columnOrder={columnOrder}
|
columnOrder={columnOrder}
|
||||||
|
groupTransactionsByDate={groupTransactionsByDate}
|
||||||
payerFilterOptions={payerFilterOptions}
|
payerFilterOptions={payerFilterOptions}
|
||||||
categoryFilterOptions={categoryFilterOptions}
|
categoryFilterOptions={categoryFilterOptions}
|
||||||
accountCardFilterOptions={accountCardFilterOptions}
|
accountCardFilterOptions={accountCardFilterOptions}
|
||||||
|
|||||||
@@ -51,6 +51,7 @@ type BuildColumnsArgs = {
|
|||||||
onConvertToRecurring?: (item: TransactionItem) => void;
|
onConvertToRecurring?: (item: TransactionItem) => void;
|
||||||
isSettlementLoading: (id: string) => boolean;
|
isSettlementLoading: (id: string) => boolean;
|
||||||
showActions: boolean;
|
showActions: boolean;
|
||||||
|
showDateGroups: boolean;
|
||||||
columnOrder?: string[] | null;
|
columnOrder?: string[] | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -115,6 +116,7 @@ function buildColumns({
|
|||||||
onConvertToRecurring,
|
onConvertToRecurring,
|
||||||
isSettlementLoading,
|
isSettlementLoading,
|
||||||
showActions,
|
showActions,
|
||||||
|
showDateGroups,
|
||||||
}: BuildColumnsArgs): ColumnDef<TransactionItem>[] {
|
}: BuildColumnsArgs): ColumnDef<TransactionItem>[] {
|
||||||
const noop = () => undefined;
|
const noop = () => undefined;
|
||||||
const handleEdit = onEdit ?? noop;
|
const handleEdit = onEdit ?? noop;
|
||||||
@@ -194,12 +196,14 @@ function buildColumns({
|
|||||||
<span className="flex items-center gap-2">
|
<span className="flex items-center gap-2">
|
||||||
<EstablishmentLogo name={name} size={32} />
|
<EstablishmentLogo name={name} size={32} />
|
||||||
<span className="flex flex-col py-0.5">
|
<span className="flex flex-col py-0.5">
|
||||||
|
{showDateGroups ? null : (
|
||||||
<span className="text-xs text-muted-foreground flex items-center gap-2">
|
<span className="text-xs text-muted-foreground flex items-center gap-2">
|
||||||
{formatDate(purchaseDate)}
|
{formatDate(purchaseDate)}
|
||||||
{dueDateLabel ? (
|
{dueDateLabel ? (
|
||||||
<span className="text-primary">{dueDateLabel}</span>
|
<span className="text-primary">{dueDateLabel}</span>
|
||||||
) : null}
|
) : null}
|
||||||
</span>
|
</span>
|
||||||
|
)}
|
||||||
<span className="flex items-center gap-1">
|
<span className="flex items-center gap-1">
|
||||||
<Tooltip>
|
<Tooltip>
|
||||||
<TooltipTrigger asChild>
|
<TooltipTrigger asChild>
|
||||||
@@ -254,6 +258,15 @@ function buildColumns({
|
|||||||
</Badge>
|
</Badge>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
|
{showDateGroups && dueDateLabel ? (
|
||||||
|
<Badge
|
||||||
|
variant="outline"
|
||||||
|
className="px-2 text-xs text-primary"
|
||||||
|
>
|
||||||
|
{dueDateLabel}
|
||||||
|
</Badge>
|
||||||
|
) : null}
|
||||||
|
|
||||||
{isAnticipated && (
|
{isAnticipated && (
|
||||||
<Tooltip>
|
<Tooltip>
|
||||||
<TooltipTrigger asChild>
|
<TooltipTrigger asChild>
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ import {
|
|||||||
TooltipContent,
|
TooltipContent,
|
||||||
TooltipTrigger,
|
TooltipTrigger,
|
||||||
} from "@/shared/components/ui/tooltip";
|
} from "@/shared/components/ui/tooltip";
|
||||||
import { formatDate } from "@/shared/utils/date";
|
import { formatDate, formatDateGroupLabel } from "@/shared/utils/date";
|
||||||
import { getConditionIcon, getPaymentMethodIcon } from "@/shared/utils/icons";
|
import { getConditionIcon, getPaymentMethodIcon } from "@/shared/utils/icons";
|
||||||
import { cn } from "@/shared/utils/ui";
|
import { cn } from "@/shared/utils/ui";
|
||||||
import type { TransactionItem } from "../types";
|
import type { TransactionItem } from "../types";
|
||||||
@@ -43,6 +43,7 @@ type TransactionsMobileListProps = {
|
|||||||
onConvertToRecurring?: (item: TransactionItem) => void;
|
onConvertToRecurring?: (item: TransactionItem) => void;
|
||||||
isSettlementLoading: (id: string) => boolean;
|
isSettlementLoading: (id: string) => boolean;
|
||||||
showActions?: boolean;
|
showActions?: boolean;
|
||||||
|
showDateGroups?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function TransactionsMobileList({
|
export function TransactionsMobileList({
|
||||||
@@ -61,7 +62,27 @@ export function TransactionsMobileList({
|
|||||||
onConvertToRecurring,
|
onConvertToRecurring,
|
||||||
isSettlementLoading,
|
isSettlementLoading,
|
||||||
showActions = true,
|
showActions = true,
|
||||||
|
showDateGroups = true,
|
||||||
}: TransactionsMobileListProps) {
|
}: TransactionsMobileListProps) {
|
||||||
|
const groups = data.reduce<
|
||||||
|
Array<{ date: string; label: string; items: TransactionItem[] }>
|
||||||
|
>((acc, item) => {
|
||||||
|
const date = item.purchaseDate?.slice(0, 10) ?? "";
|
||||||
|
const existingGroup = acc.find((group) => group.date === date);
|
||||||
|
if (existingGroup) {
|
||||||
|
existingGroup.items.push(item);
|
||||||
|
return acc;
|
||||||
|
}
|
||||||
|
|
||||||
|
acc.push({
|
||||||
|
date,
|
||||||
|
label: formatDateGroupLabel(item.purchaseDate),
|
||||||
|
items: [item],
|
||||||
|
});
|
||||||
|
return acc;
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
if (!showDateGroups) {
|
||||||
return (
|
return (
|
||||||
<div className="space-y-3 md:hidden">
|
<div className="space-y-3 md:hidden">
|
||||||
{data.map((item) => (
|
{data.map((item) => (
|
||||||
@@ -82,14 +103,54 @@ export function TransactionsMobileList({
|
|||||||
onConvertToRecurring={onConvertToRecurring}
|
onConvertToRecurring={onConvertToRecurring}
|
||||||
isSettlementLoading={isSettlementLoading}
|
isSettlementLoading={isSettlementLoading}
|
||||||
showActions={showActions}
|
showActions={showActions}
|
||||||
|
showDate
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4 md:hidden">
|
||||||
|
{groups.map((group, groupIndex) => (
|
||||||
|
<section
|
||||||
|
key={`${group.date || group.label}-${groupIndex}`}
|
||||||
|
className="space-y-2"
|
||||||
|
>
|
||||||
|
<div className="rounded-md border bg-muted/60 px-3 py-1.5 text-xs font-semibold tracking-wide text-muted-foreground">
|
||||||
|
{group.label}
|
||||||
|
</div>
|
||||||
|
<div className="space-y-3">
|
||||||
|
{group.items.map((item) => (
|
||||||
|
<TransactionMobileCard
|
||||||
|
key={item.id}
|
||||||
|
item={item}
|
||||||
|
currentUserId={currentUserId}
|
||||||
|
onEdit={onEdit}
|
||||||
|
onCopy={onCopy}
|
||||||
|
onImport={onImport}
|
||||||
|
onConfirmDelete={onConfirmDelete}
|
||||||
|
onViewDetails={onViewDetails}
|
||||||
|
onRefund={onRefund}
|
||||||
|
onToggleSettlement={onToggleSettlement}
|
||||||
|
onAnticipate={onAnticipate}
|
||||||
|
onViewAnticipationHistory={onViewAnticipationHistory}
|
||||||
|
onConvertToInstallment={onConvertToInstallment}
|
||||||
|
onConvertToRecurring={onConvertToRecurring}
|
||||||
|
isSettlementLoading={isSettlementLoading}
|
||||||
|
showActions={showActions}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
type TransactionMobileCardProps = Omit<TransactionsMobileListProps, "data"> & {
|
type TransactionMobileCardProps = Omit<TransactionsMobileListProps, "data"> & {
|
||||||
item: TransactionItem;
|
item: TransactionItem;
|
||||||
|
showDate?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
function TransactionMobileCard({
|
function TransactionMobileCard({
|
||||||
@@ -108,6 +169,7 @@ function TransactionMobileCard({
|
|||||||
onConvertToRecurring,
|
onConvertToRecurring,
|
||||||
isSettlementLoading,
|
isSettlementLoading,
|
||||||
showActions = true,
|
showActions = true,
|
||||||
|
showDate = false,
|
||||||
}: TransactionMobileCardProps) {
|
}: TransactionMobileCardProps) {
|
||||||
const installmentBadge =
|
const installmentBadge =
|
||||||
item.currentInstallment && item.installmentCount
|
item.currentInstallment && item.installmentCount
|
||||||
@@ -156,10 +218,12 @@ function TransactionMobileCard({
|
|||||||
{item.name}
|
{item.name}
|
||||||
</h3>
|
</h3>
|
||||||
<div className="mt-1 flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">
|
<div className="mt-1 flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">
|
||||||
|
{showDate ? (
|
||||||
<span className="inline-flex items-center gap-1">
|
<span className="inline-flex items-center gap-1">
|
||||||
<RiCalendarEventLine className="size-3.5" aria-hidden />
|
<RiCalendarEventLine className="size-3.5" aria-hidden />
|
||||||
{formatDate(item.purchaseDate)}
|
{formatDate(item.purchaseDate)}
|
||||||
</span>
|
</span>
|
||||||
|
) : null}
|
||||||
{dueDateLabel ? (
|
{dueDateLabel ? (
|
||||||
<span className="font-medium text-primary">
|
<span className="font-medium text-primary">
|
||||||
{dueDateLabel}
|
{dueDateLabel}
|
||||||
|
|||||||
@@ -9,13 +9,14 @@ import {
|
|||||||
getCoreRowModel,
|
getCoreRowModel,
|
||||||
getPaginationRowModel,
|
getPaginationRowModel,
|
||||||
getSortedRowModel,
|
getSortedRowModel,
|
||||||
|
type Row,
|
||||||
type RowSelectionState,
|
type RowSelectionState,
|
||||||
type SortingState,
|
type SortingState,
|
||||||
useReactTable,
|
useReactTable,
|
||||||
type VisibilityState,
|
type VisibilityState,
|
||||||
} from "@tanstack/react-table";
|
} from "@tanstack/react-table";
|
||||||
import { usePathname, useRouter, useSearchParams } from "next/navigation";
|
import { usePathname, useRouter, useSearchParams } from "next/navigation";
|
||||||
import { type ReactNode, useMemo, useState } from "react";
|
import { Fragment, type ReactNode, useMemo, useState } from "react";
|
||||||
import type {
|
import type {
|
||||||
TransactionsExportContext,
|
TransactionsExportContext,
|
||||||
TransactionsPaginationState,
|
TransactionsPaginationState,
|
||||||
@@ -37,6 +38,7 @@ import {
|
|||||||
TooltipProvider,
|
TooltipProvider,
|
||||||
TooltipTrigger,
|
TooltipTrigger,
|
||||||
} from "@/shared/components/ui/tooltip";
|
} from "@/shared/components/ui/tooltip";
|
||||||
|
import { formatDateGroupLabel } from "@/shared/utils/date";
|
||||||
import { cn } from "@/shared/utils/ui";
|
import { cn } from "@/shared/utils/ui";
|
||||||
import { TransactionsExport } from "../transactions-export";
|
import { TransactionsExport } from "../transactions-export";
|
||||||
import type {
|
import type {
|
||||||
@@ -79,6 +81,7 @@ type TransactionsTableProps = {
|
|||||||
isSettlementLoading?: (id: string) => boolean;
|
isSettlementLoading?: (id: string) => boolean;
|
||||||
showActions?: boolean;
|
showActions?: boolean;
|
||||||
showFilters?: boolean;
|
showFilters?: boolean;
|
||||||
|
groupTransactionsByDate?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function TransactionsTable({
|
export function TransactionsTable({
|
||||||
@@ -110,6 +113,7 @@ export function TransactionsTable({
|
|||||||
isSettlementLoading,
|
isSettlementLoading,
|
||||||
showActions = true,
|
showActions = true,
|
||||||
showFilters = true,
|
showFilters = true,
|
||||||
|
groupTransactionsByDate = true,
|
||||||
}: TransactionsTableProps) {
|
}: TransactionsTableProps) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const pathname = usePathname();
|
const pathname = usePathname();
|
||||||
@@ -145,12 +149,14 @@ export function TransactionsTable({
|
|||||||
onViewAnticipationHistory,
|
onViewAnticipationHistory,
|
||||||
isSettlementLoading: isSettlementLoading ?? (() => false),
|
isSettlementLoading: isSettlementLoading ?? (() => false),
|
||||||
showActions,
|
showActions,
|
||||||
|
showDateGroups: groupTransactionsByDate,
|
||||||
columnOrder: columnOrderPreference,
|
columnOrder: columnOrderPreference,
|
||||||
}),
|
}),
|
||||||
[
|
[
|
||||||
currentUserId,
|
currentUserId,
|
||||||
noteAsColumn,
|
noteAsColumn,
|
||||||
columnOrderPreference,
|
columnOrderPreference,
|
||||||
|
groupTransactionsByDate,
|
||||||
onEdit,
|
onEdit,
|
||||||
onCopy,
|
onCopy,
|
||||||
onImport,
|
onImport,
|
||||||
@@ -191,6 +197,24 @@ export function TransactionsTable({
|
|||||||
|
|
||||||
const rowModel = table.getRowModel();
|
const rowModel = table.getRowModel();
|
||||||
const hasRows = rowModel.rows.length > 0;
|
const hasRows = rowModel.rows.length > 0;
|
||||||
|
const groupedRows = rowModel.rows.reduce<
|
||||||
|
Array<{ date: string; label: string; rows: Row<TransactionItem>[] }>
|
||||||
|
>((acc, row) => {
|
||||||
|
const date = row.original.purchaseDate?.slice(0, 10) ?? "";
|
||||||
|
const existingGroup = acc.find((group) => group.date === date);
|
||||||
|
if (existingGroup) {
|
||||||
|
existingGroup.rows.push(row);
|
||||||
|
return acc;
|
||||||
|
}
|
||||||
|
|
||||||
|
acc.push({
|
||||||
|
date,
|
||||||
|
label: formatDateGroupLabel(row.original.purchaseDate),
|
||||||
|
rows: [row],
|
||||||
|
});
|
||||||
|
return acc;
|
||||||
|
}, []);
|
||||||
|
const visibleColumnCount = table.getVisibleLeafColumns().length;
|
||||||
const totalRows = isServerPaginated
|
const totalRows = isServerPaginated
|
||||||
? (serverPagination?.totalItems ?? 0)
|
? (serverPagination?.totalItems ?? 0)
|
||||||
: table.getCoreRowModel().rows.length;
|
: table.getCoreRowModel().rows.length;
|
||||||
@@ -275,6 +299,25 @@ export function TransactionsTable({
|
|||||||
|
|
||||||
const showTopControls =
|
const showTopControls =
|
||||||
Boolean(createSlot) || Boolean(onMassAdd) || showFilters;
|
Boolean(createSlot) || Boolean(onMassAdd) || showFilters;
|
||||||
|
const renderTransactionRow = (row: Row<TransactionItem>) => (
|
||||||
|
<TableRow
|
||||||
|
key={row.id}
|
||||||
|
className={cn(
|
||||||
|
row.original.paymentMethod === "Boleto" &&
|
||||||
|
row.original.dueDate &&
|
||||||
|
!row.original.isSettled &&
|
||||||
|
new Date(row.original.dueDate) < new Date()
|
||||||
|
? "bg-destructive/3 hover:bg-destructive/5"
|
||||||
|
: undefined,
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{row.getVisibleCells().map((cell) => (
|
||||||
|
<TableCell key={cell.id}>
|
||||||
|
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
||||||
|
</TableCell>
|
||||||
|
))}
|
||||||
|
</TableRow>
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<TooltipProvider>
|
<TooltipProvider>
|
||||||
@@ -366,7 +409,7 @@ export function TransactionsTable({
|
|||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
<Card className="py-2">
|
<Card className="py-2">
|
||||||
<CardContent className="px-2 py-4 sm:px-4">
|
<CardContent className="px-2 sm:px-4">
|
||||||
{hasRows ? (
|
{hasRows ? (
|
||||||
<>
|
<>
|
||||||
<TransactionsMobileList
|
<TransactionsMobileList
|
||||||
@@ -383,6 +426,7 @@ export function TransactionsTable({
|
|||||||
onViewAnticipationHistory={onViewAnticipationHistory}
|
onViewAnticipationHistory={onViewAnticipationHistory}
|
||||||
isSettlementLoading={isSettlementLoading ?? (() => false)}
|
isSettlementLoading={isSettlementLoading ?? (() => false)}
|
||||||
showActions={showActions}
|
showActions={showActions}
|
||||||
|
showDateGroups={groupTransactionsByDate}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<div className="hidden overflow-x-auto md:block">
|
<div className="hidden overflow-x-auto md:block">
|
||||||
@@ -407,28 +451,23 @@ export function TransactionsTable({
|
|||||||
))}
|
))}
|
||||||
</TableHeader>
|
</TableHeader>
|
||||||
<TableBody>
|
<TableBody>
|
||||||
{rowModel.rows.map((row) => (
|
{groupTransactionsByDate
|
||||||
<TableRow
|
? groupedRows.map((group, groupIndex) => (
|
||||||
key={row.id}
|
<Fragment
|
||||||
className={cn(
|
key={`${group.date || group.label}-${groupIndex}`}
|
||||||
row.original.paymentMethod === "Boleto" &&
|
|
||||||
row.original.dueDate &&
|
|
||||||
!row.original.isSettled &&
|
|
||||||
new Date(row.original.dueDate) < new Date()
|
|
||||||
? "bg-destructive/3 hover:bg-destructive/5"
|
|
||||||
: undefined,
|
|
||||||
)}
|
|
||||||
>
|
>
|
||||||
{row.getVisibleCells().map((cell) => (
|
<TableRow className="border-y bg-muted/40 hover:bg-muted/60">
|
||||||
<TableCell key={cell.id}>
|
<TableCell
|
||||||
{flexRender(
|
colSpan={visibleColumnCount}
|
||||||
cell.column.columnDef.cell,
|
className="h-9 px-3 py-2 text-xs font-semibold text-muted-foreground"
|
||||||
cell.getContext(),
|
>
|
||||||
)}
|
{group.label}
|
||||||
</TableCell>
|
</TableCell>
|
||||||
))}
|
|
||||||
</TableRow>
|
</TableRow>
|
||||||
))}
|
{group.rows.map(renderTransactionRow)}
|
||||||
|
</Fragment>
|
||||||
|
))
|
||||||
|
: rowModel.rows.map(renderTransactionRow)}
|
||||||
</TableBody>
|
</TableBody>
|
||||||
</Table>
|
</Table>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
24
src/features/transactions/lib/ofx-import-fingerprint.ts
Normal file
24
src/features/transactions/lib/ofx-import-fingerprint.ts
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
import "server-only";
|
||||||
|
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import {
|
||||||
|
buildOfxFingerprintPayload,
|
||||||
|
type OfxIdentityRow,
|
||||||
|
type OfxImportDestination,
|
||||||
|
} from "@/shared/lib/import/ofx-identity";
|
||||||
|
|
||||||
|
type CreateOfxImportFingerprintInput = {
|
||||||
|
source: string;
|
||||||
|
accountNumber: string | null;
|
||||||
|
destination: OfxImportDestination;
|
||||||
|
row: OfxIdentityRow;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function createOfxImportFingerprint(
|
||||||
|
input: CreateOfxImportFingerprintInput,
|
||||||
|
): string | null {
|
||||||
|
const payload = buildOfxFingerprintPayload(input);
|
||||||
|
if (!payload) return null;
|
||||||
|
|
||||||
|
return createHash("sha256").update(payload).digest("hex");
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@ import {
|
|||||||
ilike,
|
ilike,
|
||||||
inArray,
|
inArray,
|
||||||
isNotNull,
|
isNotNull,
|
||||||
|
isNull,
|
||||||
lte,
|
lte,
|
||||||
or,
|
or,
|
||||||
sql,
|
sql,
|
||||||
@@ -384,6 +385,7 @@ export const buildTransactionWhere = ({
|
|||||||
cardId,
|
cardId,
|
||||||
accountId,
|
accountId,
|
||||||
payerId,
|
payerId,
|
||||||
|
hideAnticipatedInstallments = false,
|
||||||
}: {
|
}: {
|
||||||
userId: string;
|
userId: string;
|
||||||
period: string;
|
period: string;
|
||||||
@@ -392,6 +394,7 @@ export const buildTransactionWhere = ({
|
|||||||
cardId?: string;
|
cardId?: string;
|
||||||
accountId?: string;
|
accountId?: string;
|
||||||
payerId?: string;
|
payerId?: string;
|
||||||
|
hideAnticipatedInstallments?: boolean;
|
||||||
}): SQL[] => {
|
}): SQL[] => {
|
||||||
const where: SQL[] = [eq(transactions.userId, userId)];
|
const where: SQL[] = [eq(transactions.userId, userId)];
|
||||||
|
|
||||||
@@ -421,6 +424,15 @@ export const buildTransactionWhere = ({
|
|||||||
where.push(eq(transactions.payerId, payerId));
|
where.push(eq(transactions.payerId, payerId));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (hideAnticipatedInstallments) {
|
||||||
|
where.push(
|
||||||
|
or(
|
||||||
|
isNull(transactions.isAnticipated),
|
||||||
|
eq(transactions.isAnticipated, false),
|
||||||
|
) as SQL,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
if (cardId) {
|
if (cardId) {
|
||||||
where.push(eq(transactions.cardId, cardId));
|
where.push(eq(transactions.cardId, cardId));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -102,7 +102,7 @@ export function EstablishmentLogoPicker({
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Popover open={open} onOpenChange={onOpenChange}>
|
<Popover modal open={open} onOpenChange={onOpenChange}>
|
||||||
<PopoverTrigger asChild>{children}</PopoverTrigger>
|
<PopoverTrigger asChild>{children}</PopoverTrigger>
|
||||||
<PopoverContent className="w-80 p-3" align="start" side="bottom">
|
<PopoverContent className="w-80 p-3" align="start" side="bottom">
|
||||||
<p className="mb-2 text-muted-foreground text-xs">
|
<p className="mb-2 text-muted-foreground text-xs">
|
||||||
|
|||||||
38
src/shared/components/feedback/content-error-boundary.tsx
Normal file
38
src/shared/components/feedback/content-error-boundary.tsx
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { RiErrorWarningLine } from "@remixicon/react";
|
||||||
|
import { catchError, type ErrorInfo } from "next/error";
|
||||||
|
import { EmptyState } from "@/shared/components/feedback/empty-state";
|
||||||
|
import { Button } from "@/shared/components/ui/button";
|
||||||
|
|
||||||
|
type ContentErrorBoundaryProps = {
|
||||||
|
title: string;
|
||||||
|
description: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
function ContentErrorFallback(
|
||||||
|
{ title, description }: ContentErrorBoundaryProps,
|
||||||
|
{ retry }: ErrorInfo,
|
||||||
|
) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
role="alert"
|
||||||
|
className="flex min-h-64 w-full items-center justify-center"
|
||||||
|
>
|
||||||
|
<EmptyState
|
||||||
|
title={title}
|
||||||
|
description={description}
|
||||||
|
media={<RiErrorWarningLine className="size-5 text-destructive" />}
|
||||||
|
mediaVariant="icon"
|
||||||
|
className="min-h-64 border border-dashed"
|
||||||
|
>
|
||||||
|
<Button type="button" variant="outline" onClick={retry}>
|
||||||
|
Tentar novamente
|
||||||
|
</Button>
|
||||||
|
</EmptyState>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const ContentErrorBoundary =
|
||||||
|
catchError<ContentErrorBoundaryProps>(ContentErrorFallback);
|
||||||
@@ -93,6 +93,7 @@ export default function MonthNavigation() {
|
|||||||
<Popover open={isPickerOpen} onOpenChange={setIsPickerOpen}>
|
<Popover open={isPickerOpen} onOpenChange={setIsPickerOpen}>
|
||||||
<PopoverTrigger asChild>
|
<PopoverTrigger asChild>
|
||||||
<Button
|
<Button
|
||||||
|
type="button"
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="sm"
|
size="sm"
|
||||||
disabled={isPending}
|
disabled={isPending}
|
||||||
|
|||||||
@@ -44,9 +44,10 @@ export function PeriodPicker({
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Popover open={open} onOpenChange={setOpen}>
|
<Popover modal open={open} onOpenChange={setOpen}>
|
||||||
<PopoverTrigger asChild>
|
<PopoverTrigger asChild>
|
||||||
<Button
|
<Button
|
||||||
|
type="button"
|
||||||
variant={variant}
|
variant={variant}
|
||||||
size={size}
|
size={size}
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
|
|||||||
@@ -197,6 +197,7 @@ function CalendarDayButton({
|
|||||||
return (
|
return (
|
||||||
<Button
|
<Button
|
||||||
ref={ref}
|
ref={ref}
|
||||||
|
type="button"
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="icon"
|
size="icon"
|
||||||
data-day={day.date.toLocaleDateString()}
|
data-day={day.date.toLocaleDateString()}
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ function Checkbox({
|
|||||||
<CheckboxPrimitive.Root
|
<CheckboxPrimitive.Root
|
||||||
data-slot="checkbox"
|
data-slot="checkbox"
|
||||||
className={cn(
|
className={cn(
|
||||||
"peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary data-[state=indeterminate]:bg-primary data-[state=indeterminate]:text-primary-foreground data-[state=indeterminate]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-lg border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
"peer border-input dark:bg-input/40 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary data-[state=indeterminate]:bg-primary data-[state=indeterminate]:text-primary-foreground data-[state=indeterminate]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-3.5 shrink-0 rounded border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
||||||
className,
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
|
|||||||
@@ -148,7 +148,7 @@ export function DatePicker({
|
|||||||
required={required}
|
required={required}
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
/>
|
/>
|
||||||
<Popover open={open} onOpenChange={setOpen}>
|
<Popover modal open={open} onOpenChange={setOpen}>
|
||||||
<PopoverTrigger asChild>
|
<PopoverTrigger asChild>
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
|
|||||||
@@ -128,6 +128,7 @@ function MonthCal({
|
|||||||
</div>
|
</div>
|
||||||
<div className="space-x-1 flex items-center">
|
<div className="space-x-1 flex items-center">
|
||||||
<button
|
<button
|
||||||
|
type="button"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setMenuYear(menuYear - 1);
|
setMenuYear(menuYear - 1);
|
||||||
if (onYearBackward) onYearBackward();
|
if (onYearBackward) onYearBackward();
|
||||||
@@ -140,6 +141,7 @@ function MonthCal({
|
|||||||
<RiArrowLeftSFill className="opacity-50 size-4" />
|
<RiArrowLeftSFill className="opacity-50 size-4" />
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
|
type="button"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setMenuYear(menuYear + 1);
|
setMenuYear(menuYear + 1);
|
||||||
if (onYearForward) onYearForward();
|
if (onYearForward) onYearForward();
|
||||||
@@ -165,6 +167,7 @@ function MonthCal({
|
|||||||
className="h-10 w-1/4 text-center text-sm p-0 relative [&:has([aria-selected].day-range-end)]:rounded-r-md [&:has([aria-selected].day-outside)]:bg-accent/50 [&:has([aria-selected])]:bg-accent first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md focus-within:relative focus-within:z-20"
|
className="h-10 w-1/4 text-center text-sm p-0 relative [&:has([aria-selected].day-range-end)]:rounded-r-md [&:has([aria-selected].day-outside)]:bg-accent/50 [&:has([aria-selected])]:bg-accent first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md focus-within:relative focus-within:z-20"
|
||||||
>
|
>
|
||||||
<button
|
<button
|
||||||
|
type="button"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setMonth(m.number);
|
setMonth(m.number);
|
||||||
setYear(menuYear);
|
setYear(menuYear);
|
||||||
|
|||||||
69
src/shared/lib/import/ofx-identity.ts
Normal file
69
src/shared/lib/import/ofx-identity.ts
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
import { formatDecimalForDbRequired } from "@/shared/utils/currency";
|
||||||
|
|
||||||
|
export type OfxImportDestination = {
|
||||||
|
type: "account" | "card";
|
||||||
|
id: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type OfxIdentityRow = {
|
||||||
|
externalId: string | null;
|
||||||
|
externalIdOccurrence: number;
|
||||||
|
date: string;
|
||||||
|
amount: number;
|
||||||
|
transactionType: "income" | "expense";
|
||||||
|
sourceDescription: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type OfxIdentityInput = {
|
||||||
|
source: string;
|
||||||
|
accountNumber: string | null;
|
||||||
|
destination: OfxImportDestination;
|
||||||
|
row: OfxIdentityRow;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function normalizeOfxIdentityText(value: string): string {
|
||||||
|
return value.normalize("NFKC").trim().replace(/\s+/g, " ").toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildOfxOccurrenceKey(
|
||||||
|
row: Omit<OfxIdentityRow, "externalIdOccurrence">,
|
||||||
|
): string | null {
|
||||||
|
if (!row.externalId) return null;
|
||||||
|
|
||||||
|
const signedAmount =
|
||||||
|
row.transactionType === "expense" ? -row.amount : row.amount;
|
||||||
|
|
||||||
|
return JSON.stringify([
|
||||||
|
row.externalId.trim(),
|
||||||
|
row.date,
|
||||||
|
formatDecimalForDbRequired(signedAmount),
|
||||||
|
row.transactionType,
|
||||||
|
normalizeOfxIdentityText(row.sourceDescription),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildOfxFingerprintPayload({
|
||||||
|
source,
|
||||||
|
accountNumber,
|
||||||
|
destination,
|
||||||
|
row,
|
||||||
|
}: OfxIdentityInput): string | null {
|
||||||
|
if (!row.externalId) return null;
|
||||||
|
|
||||||
|
const signedAmount =
|
||||||
|
row.transactionType === "expense" ? -row.amount : row.amount;
|
||||||
|
|
||||||
|
return JSON.stringify([
|
||||||
|
"openmonetis-ofx-v1",
|
||||||
|
normalizeOfxIdentityText(source),
|
||||||
|
normalizeOfxIdentityText(accountNumber ?? ""),
|
||||||
|
destination.type,
|
||||||
|
destination.id,
|
||||||
|
row.externalId.trim(),
|
||||||
|
row.date,
|
||||||
|
formatDecimalForDbRequired(signedAmount),
|
||||||
|
row.transactionType,
|
||||||
|
normalizeOfxIdentityText(row.sourceDescription),
|
||||||
|
row.externalIdOccurrence,
|
||||||
|
]);
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { buildOfxOccurrenceKey } from "./ofx-identity";
|
||||||
import type { ImportedTransaction, ImportStatement } from "./types";
|
import type { ImportedTransaction, ImportStatement } from "./types";
|
||||||
|
|
||||||
// Extrai o valor de uma tag leaf do OFX SGML: <TAG>valor
|
// Extrai o valor de uma tag leaf do OFX SGML: <TAG>valor
|
||||||
@@ -32,6 +33,7 @@ export function parseOfx(content: string): ImportStatement {
|
|||||||
|
|
||||||
// Transações
|
// Transações
|
||||||
const blocks = xml.match(/<STMTTRN>[\s\S]*?<\/STMTTRN>/g) ?? [];
|
const blocks = xml.match(/<STMTTRN>[\s\S]*?<\/STMTTRN>/g) ?? [];
|
||||||
|
const occurrenceCounts = new Map<string, number>();
|
||||||
const transactions: ImportedTransaction[] = blocks.map((block) => {
|
const transactions: ImportedTransaction[] = blocks.map((block) => {
|
||||||
const trnType = getField(block, "TRNTYPE") ?? "DEBIT";
|
const trnType = getField(block, "TRNTYPE") ?? "DEBIT";
|
||||||
const dtPosted = getField(block, "DTPOSTED") ?? "";
|
const dtPosted = getField(block, "DTPOSTED") ?? "";
|
||||||
@@ -41,16 +43,30 @@ export function parseOfx(content: string): ImportStatement {
|
|||||||
const name = getField(block, "NAME");
|
const name = getField(block, "NAME");
|
||||||
|
|
||||||
const amount = Number.parseFloat(trnAmt.replace(",", "."));
|
const amount = Number.parseFloat(trnAmt.replace(",", "."));
|
||||||
const transactionType =
|
const transactionType: ImportedTransaction["transactionType"] =
|
||||||
amount > 0 || trnType === "CREDIT" ? "income" : "expense";
|
amount > 0 || trnType === "CREDIT" ? "income" : "expense";
|
||||||
|
const description = memo ?? name ?? "";
|
||||||
return {
|
const transaction = {
|
||||||
externalId: fitId,
|
externalId: fitId,
|
||||||
date: parseOfxDate(dtPosted),
|
date: parseOfxDate(dtPosted),
|
||||||
amount: Math.abs(amount),
|
amount: Math.abs(amount),
|
||||||
description: memo ?? name ?? "",
|
description,
|
||||||
|
sourceDescription: description,
|
||||||
transactionType,
|
transactionType,
|
||||||
};
|
};
|
||||||
|
const occurrenceKey = buildOfxOccurrenceKey(transaction);
|
||||||
|
const externalIdOccurrence = occurrenceKey
|
||||||
|
? (occurrenceCounts.get(occurrenceKey) ?? 0)
|
||||||
|
: 0;
|
||||||
|
|
||||||
|
if (occurrenceKey) {
|
||||||
|
occurrenceCounts.set(occurrenceKey, externalIdOccurrence + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
...transaction,
|
||||||
|
externalIdOccurrence,
|
||||||
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
const isCreditCard = xml.includes("<CREDITCARDMSGSRSV1>");
|
const isCreditCard = xml.includes("<CREDITCARDMSGSRSV1>");
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
export type ImportedTransaction = {
|
export type ImportedTransaction = {
|
||||||
externalId: string | null; // FITID do OFX
|
externalId: string | null; // FITID do OFX
|
||||||
|
externalIdOccurrence: number; // posição entre registros OFX idênticos
|
||||||
date: string; // YYYY-MM-DD
|
date: string; // YYYY-MM-DD
|
||||||
amount: number; // positivo = receita, negativo = despesa
|
amount: number; // positivo = receita, negativo = despesa
|
||||||
description: string; // MEMO ou NAME
|
description: string; // MEMO ou NAME
|
||||||
|
sourceDescription: string; // descrição original, preservada para deduplicação
|
||||||
transactionType: "income" | "expense";
|
transactionType: "income" | "expense";
|
||||||
categoryRaw?: string | null;
|
categoryRaw?: string | null;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -105,9 +105,11 @@ export async function parseXls(buffer: ArrayBuffer): Promise<ImportStatement> {
|
|||||||
|
|
||||||
transactions.push({
|
transactions.push({
|
||||||
externalId: null,
|
externalId: null,
|
||||||
|
externalIdOccurrence: 0,
|
||||||
date,
|
date,
|
||||||
amount,
|
amount,
|
||||||
description,
|
description,
|
||||||
|
sourceDescription: description,
|
||||||
transactionType,
|
transactionType,
|
||||||
categoryRaw,
|
categoryRaw,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -331,6 +331,45 @@ export function formatDate(value: string | Date | null | undefined): string {
|
|||||||
.replace(" de", "");
|
.replace(" de", "");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Formats a date-only value as a compact group label.
|
||||||
|
* @example
|
||||||
|
* formatDateGroupLabel("2026-06-26") // "SEX, 26 JUN 2026"
|
||||||
|
*/
|
||||||
|
export function formatDateGroupLabel(
|
||||||
|
value: string | Date | null | undefined,
|
||||||
|
): string {
|
||||||
|
const dateString = toDateOnlyString(value);
|
||||||
|
if (!dateString) {
|
||||||
|
return "—";
|
||||||
|
}
|
||||||
|
|
||||||
|
const parsed = parseUtcDateString(dateString);
|
||||||
|
if (!parsed) {
|
||||||
|
return "—";
|
||||||
|
}
|
||||||
|
|
||||||
|
const parts = new Intl.DateTimeFormat("pt-BR", {
|
||||||
|
weekday: "short",
|
||||||
|
day: "2-digit",
|
||||||
|
month: "short",
|
||||||
|
year: "numeric",
|
||||||
|
timeZone: "UTC",
|
||||||
|
}).formatToParts(parsed);
|
||||||
|
const weekday = parts.find((part) => part.type === "weekday")?.value;
|
||||||
|
const day = parts.find((part) => part.type === "day")?.value;
|
||||||
|
const month = parts.find((part) => part.type === "month")?.value;
|
||||||
|
const year = parts.find((part) => part.type === "year")?.value;
|
||||||
|
|
||||||
|
if (!weekday || !day || !month || !year) {
|
||||||
|
return "—";
|
||||||
|
}
|
||||||
|
|
||||||
|
return `${weekday.replace(".", "").toUpperCase()}, ${day} ${month
|
||||||
|
.replace(".", "")
|
||||||
|
.toUpperCase()} ${year}`;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Formats a date-only value (YYYY-MM-DD) using UTC to preserve the civil day
|
* Formats a date-only value (YYYY-MM-DD) using UTC to preserve the civil day
|
||||||
*/
|
*/
|
||||||
|
|||||||
Reference in New Issue
Block a user