Compare commits
32 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bf4138db82 | ||
|
|
ed9196797b | ||
|
|
532186fe39 | ||
|
|
a2ce7f1283 | ||
|
|
f3c3d98aeb | ||
|
|
24709ec232 | ||
|
|
2fd94118f2 | ||
|
|
01f161f011 | ||
|
|
4741087feb | ||
|
|
32b190ab4e | ||
|
|
d06bac5624 | ||
|
|
be6fa6dcfc | ||
|
|
954fdc148e | ||
|
|
fb1759c2ee | ||
|
|
b1b2f5fe0d | ||
|
|
4d62abfc6b | ||
|
|
1660f68a4b | ||
|
|
d363662548 | ||
|
|
129295d2e2 | ||
|
|
4b5cdf81b8 | ||
|
|
558197e870 | ||
|
|
2fd6e3c323 | ||
|
|
833845b5cf | ||
|
|
4cbdddb12e | ||
|
|
c81584095b | ||
|
|
8ccc4479be | ||
|
|
2cead626ab | ||
|
|
811a035cb0 | ||
|
|
356801324c | ||
|
|
b443fb010a | ||
|
|
026dff5399 | ||
|
|
18b6a6a470 |
@@ -17,8 +17,15 @@ POSTGRES_DB=openmonetis_db
|
|||||||
# Gere com: openssl rand -base64 32
|
# Gere com: openssl rand -base64 32
|
||||||
BETTER_AUTH_SECRET=your-secret-key-here-change-this
|
BETTER_AUTH_SECRET=your-secret-key-here-change-this
|
||||||
BETTER_AUTH_URL=http://localhost:3000
|
BETTER_AUTH_URL=http://localhost:3000
|
||||||
|
|
||||||
|
# Origins adicionais confiáveis para o Better Auth.
|
||||||
|
# Útil para Cloudflare Tunnel, reverse proxy e URLs diferentes de BETTER_AUTH_URL.
|
||||||
|
# Separe múltiplas origins por vírgula.
|
||||||
|
# Exemplo: https://*.trycloudflare.com,https://openmonetis.seudominio.com
|
||||||
|
BETTER_AUTH_TRUSTED_ORIGINS=
|
||||||
# Defina como true para bloquear novos cadastros
|
# Defina como true para bloquear novos cadastros
|
||||||
DISABLE_SIGNUP=false
|
DISABLE_SIGNUP=false
|
||||||
|
|
||||||
# Duração de sessões persistentes quando "Manter conectado" estiver marcado
|
# Duração de sessões persistentes quando "Manter conectado" estiver marcado
|
||||||
AUTH_SESSION_EXPIRES_IN_DAYS=30
|
AUTH_SESSION_EXPIRES_IN_DAYS=30
|
||||||
AUTH_SESSION_UPDATE_AGE_HOURS=24
|
AUTH_SESSION_UPDATE_AGE_HOURS=24
|
||||||
|
|||||||
57
.github/workflows/ci.yml
vendored
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
name: CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
|
pull_request:
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: ci-${{ github.workflow }}-${{ github.ref }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
quality:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v5
|
||||||
|
|
||||||
|
- name: Setup pnpm
|
||||||
|
uses: pnpm/action-setup@v4
|
||||||
|
|
||||||
|
- name: Setup Node.js
|
||||||
|
uses: actions/setup-node@v5
|
||||||
|
with:
|
||||||
|
node-version: 22
|
||||||
|
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
|
||||||
|
run: pnpm install --frozen-lockfile
|
||||||
|
|
||||||
|
- name: Generate Next.js types
|
||||||
|
run: pnpm exec next typegen
|
||||||
|
|
||||||
|
- name: Typecheck
|
||||||
|
run: pnpm exec tsc --noEmit
|
||||||
|
|
||||||
|
- name: Lint
|
||||||
|
run: pnpm run lint
|
||||||
|
|
||||||
|
- name: Build application
|
||||||
|
run: pnpm run build
|
||||||
87
.github/workflows/docker-publish.yml
vendored
@@ -1,87 +0,0 @@
|
|||||||
name: Build and Push to Docker Hub
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- main
|
|
||||||
tags:
|
|
||||||
- 'v*.*.*'
|
|
||||||
pull_request:
|
|
||||||
branches:
|
|
||||||
- main
|
|
||||||
workflow_dispatch:
|
|
||||||
|
|
||||||
env:
|
|
||||||
DOCKER_IMAGE_NAME: openmonetis
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
quality:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Checkout repository
|
|
||||||
uses: actions/checkout@v5
|
|
||||||
|
|
||||||
- name: Setup pnpm
|
|
||||||
uses: pnpm/action-setup@v4
|
|
||||||
|
|
||||||
- name: Setup Node.js
|
|
||||||
uses: actions/setup-node@v5
|
|
||||||
with:
|
|
||||||
node-version: 22
|
|
||||||
cache: 'pnpm'
|
|
||||||
|
|
||||||
- name: Install dependencies
|
|
||||||
run: pnpm install --frozen-lockfile
|
|
||||||
|
|
||||||
- name: Lint
|
|
||||||
run: pnpm run lint
|
|
||||||
|
|
||||||
build-and-push:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: quality
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
packages: write
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Checkout repository
|
|
||||||
uses: actions/checkout@v5
|
|
||||||
|
|
||||||
- name: Set up Docker Buildx
|
|
||||||
uses: docker/setup-buildx-action@v3
|
|
||||||
|
|
||||||
- name: Log in to Docker Hub
|
|
||||||
if: github.event_name != 'pull_request'
|
|
||||||
uses: docker/login-action@v3
|
|
||||||
with:
|
|
||||||
username: ${{ secrets.DOCKER_USERNAME }}
|
|
||||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
|
||||||
|
|
||||||
- name: Extract metadata (tags, labels)
|
|
||||||
id: meta
|
|
||||||
uses: docker/metadata-action@v5
|
|
||||||
with:
|
|
||||||
images: ${{ secrets.DOCKER_USERNAME }}/${{ env.DOCKER_IMAGE_NAME }}
|
|
||||||
tags: |
|
|
||||||
type=ref,event=branch
|
|
||||||
type=ref,event=pr
|
|
||||||
type=semver,pattern={{version}}
|
|
||||||
type=semver,pattern={{major}}.{{minor}}
|
|
||||||
type=semver,pattern={{major}}
|
|
||||||
type=raw,value=latest,enable={{is_default_branch}}
|
|
||||||
type=sha,prefix={{branch}}-
|
|
||||||
|
|
||||||
- name: Build and push Docker image
|
|
||||||
uses: docker/build-push-action@v5
|
|
||||||
with:
|
|
||||||
context: .
|
|
||||||
file: ./Dockerfile
|
|
||||||
push: ${{ github.event_name != 'pull_request' }}
|
|
||||||
tags: ${{ steps.meta.outputs.tags }}
|
|
||||||
labels: ${{ steps.meta.outputs.labels }}
|
|
||||||
cache-from: type=gha
|
|
||||||
cache-to: type=gha,mode=max
|
|
||||||
platforms: linux/amd64,linux/arm64
|
|
||||||
|
|
||||||
- name: Image digest
|
|
||||||
run: echo ${{ steps.meta.outputs.digest }}
|
|
||||||
157
.github/workflows/release.yml
vendored
@@ -2,58 +2,151 @@ name: Release
|
|||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches:
|
tags:
|
||||||
- main
|
- "v*.*.*"
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: release-${{ github.ref }}
|
||||||
|
cancel-in-progress: false
|
||||||
|
|
||||||
|
env:
|
||||||
|
DOCKER_IMAGE_NAME: openmonetis
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
release:
|
quality:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v5
|
||||||
|
|
||||||
|
- name: Validate release version
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
TAG_VERSION="${GITHUB_REF_NAME#v}"
|
||||||
|
PACKAGE_VERSION="$(jq -r '.version' package.json)"
|
||||||
|
|
||||||
|
if [[ ! "$TAG_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||||
|
echo "A tag $GITHUB_REF_NAME não segue o formato vX.Y.Z."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ "$TAG_VERSION" != "$PACKAGE_VERSION" ]]; then
|
||||||
|
echo "A tag $GITHUB_REF_NAME não corresponde à versão $PACKAGE_VERSION do package.json."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ! grep -Fq "## [$TAG_VERSION]" CHANGELOG.md; then
|
||||||
|
echo "A versão $TAG_VERSION não foi encontrada no CHANGELOG.md."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Setup pnpm
|
||||||
|
uses: pnpm/action-setup@v4
|
||||||
|
|
||||||
|
- name: Setup Node.js
|
||||||
|
uses: actions/setup-node@v5
|
||||||
|
with:
|
||||||
|
node-version: 22
|
||||||
|
cache: pnpm
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: pnpm install --frozen-lockfile
|
||||||
|
|
||||||
|
- name: Generate Next.js types
|
||||||
|
run: pnpm exec next typegen
|
||||||
|
|
||||||
|
- name: Typecheck
|
||||||
|
run: pnpm exec tsc --noEmit
|
||||||
|
|
||||||
|
- name: Lint
|
||||||
|
run: pnpm run lint
|
||||||
|
|
||||||
|
docker:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: quality
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v5
|
||||||
|
|
||||||
|
- name: Set up Docker Buildx
|
||||||
|
uses: docker/setup-buildx-action@v3
|
||||||
|
|
||||||
|
- name: Log in to Docker Hub
|
||||||
|
uses: docker/login-action@v3
|
||||||
|
with:
|
||||||
|
username: ${{ secrets.DOCKER_USERNAME }}
|
||||||
|
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||||
|
|
||||||
|
- name: Extract Docker metadata
|
||||||
|
id: meta
|
||||||
|
uses: docker/metadata-action@v5
|
||||||
|
with:
|
||||||
|
images: ${{ secrets.DOCKER_USERNAME }}/${{ env.DOCKER_IMAGE_NAME }}
|
||||||
|
tags: |
|
||||||
|
type=semver,pattern={{version}}
|
||||||
|
type=semver,pattern={{major}}.{{minor}}
|
||||||
|
type=semver,pattern={{major}}
|
||||||
|
type=raw,value=latest
|
||||||
|
|
||||||
|
- name: Build and push Docker image
|
||||||
|
id: build
|
||||||
|
uses: docker/build-push-action@v5
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
file: ./Dockerfile
|
||||||
|
push: true
|
||||||
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
|
labels: ${{ steps.meta.outputs.labels }}
|
||||||
|
cache-from: type=gha
|
||||||
|
cache-to: type=gha,mode=max
|
||||||
|
platforms: linux/amd64,linux/arm64
|
||||||
|
|
||||||
|
- name: Image digest
|
||||||
|
run: echo "${{ steps.build.outputs.digest }}"
|
||||||
|
|
||||||
|
github-release:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: docker
|
||||||
permissions:
|
permissions:
|
||||||
contents: write
|
contents: write
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@v5
|
uses: actions/checkout@v5
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
|
|
||||||
- name: Read version from package.json
|
|
||||||
id: version
|
|
||||||
run: |
|
|
||||||
VERSION=$(jq -r '.version' package.json)
|
|
||||||
echo "value=$VERSION" >> $GITHUB_OUTPUT
|
|
||||||
echo "tag=v$VERSION" >> $GITHUB_OUTPUT
|
|
||||||
|
|
||||||
- name: Check if tag already exists
|
|
||||||
id: tag_check
|
|
||||||
run: |
|
|
||||||
if git ls-remote --tags origin "refs/tags/v${{ steps.version.outputs.value }}" | grep -q .; then
|
|
||||||
echo "exists=true" >> $GITHUB_OUTPUT
|
|
||||||
else
|
|
||||||
echo "exists=false" >> $GITHUB_OUTPUT
|
|
||||||
fi
|
|
||||||
|
|
||||||
- name: Extract changelog for this version
|
- name: Extract changelog for this version
|
||||||
if: steps.tag_check.outputs.exists == 'false'
|
|
||||||
id: changelog
|
id: changelog
|
||||||
|
shell: bash
|
||||||
run: |
|
run: |
|
||||||
VERSION="${{ steps.version.outputs.value }}"
|
VERSION="${GITHUB_REF_NAME#v}"
|
||||||
# Extrai o bloco entre ## [X.Y.Z] e o próximo ## [
|
NOTES=$(awk -v version="$VERSION" '
|
||||||
NOTES=$(awk "/^## \[$VERSION\]/{found=1; next} found && /^## \[/{exit} found{print}" CHANGELOG.md)
|
index($0, "## [" version "]") == 1 { found=1; next }
|
||||||
# Remove linhas em branco do início e fim
|
found && /^## \[/ { exit }
|
||||||
NOTES=$(echo "$NOTES" | sed '/./,$!d' | sed -e :a -e '/^\n*$/{$d;N;ba}')
|
found && !started && /^[[:space:]]*$/ { next }
|
||||||
|
found { started=1; print }
|
||||||
|
' CHANGELOG.md)
|
||||||
|
|
||||||
|
if [[ -z "$NOTES" ]]; then
|
||||||
|
echo "Não foi possível extrair as notas da versão $VERSION."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
{
|
{
|
||||||
echo "notes<<EOF"
|
echo "notes<<EOF"
|
||||||
echo "$NOTES"
|
echo "$NOTES"
|
||||||
echo "EOF"
|
echo "EOF"
|
||||||
} >> $GITHUB_OUTPUT
|
} >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
- name: Create tag and GitHub Release
|
- name: Create GitHub Release
|
||||||
if: steps.tag_check.outputs.exists == 'false'
|
|
||||||
uses: softprops/action-gh-release@v2
|
uses: softprops/action-gh-release@v2
|
||||||
with:
|
with:
|
||||||
tag_name: ${{ steps.version.outputs.tag }}
|
tag_name: ${{ github.ref_name }}
|
||||||
name: ${{ steps.version.outputs.tag }}
|
name: ${{ github.ref_name }}
|
||||||
body: ${{ steps.changelog.outputs.notes }}
|
body: ${{ steps.changelog.outputs.notes }}
|
||||||
draft: false
|
draft: false
|
||||||
prerelease: false
|
prerelease: false
|
||||||
|
|||||||
1
.gitignore
vendored
@@ -105,7 +105,6 @@ docker-compose.override.yml
|
|||||||
.gemini/
|
.gemini/
|
||||||
.cursor/
|
.cursor/
|
||||||
QWEN.md
|
QWEN.md
|
||||||
AGENTS.md
|
|
||||||
.codex
|
.codex
|
||||||
# === Backups locais ===
|
# === Backups locais ===
|
||||||
/backup/
|
/backup/
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# CLAUDE.md - OpenMonetis
|
# AGENTS.md - OpenMonetis
|
||||||
|
|
||||||
> Self-hosted personal finance app (Next.js 16, React 19, PostgreSQL, Drizzle ORM, Better Auth, Tailwind 4, shadcn/ui).
|
> 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.
|
> Portuguese UI, English folders/imports. Linter: Biome 2.x. Package manager: pnpm.
|
||||||
@@ -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**: 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...").
|
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 -->
|
||||||
134
CHANGELOG.md
@@ -5,6 +5,140 @@ 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
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
### Alterado
|
||||||
|
- CI: pull requests e pushes na `main` agora executam geração de tipos, verificação TypeScript, lint e build sem publicar imagens.
|
||||||
|
- Releases: tags `vX.Y.Z` agora validam sua correspondência com o `package.json` e o `CHANGELOG.md` antes de publicar as imagens Docker e criar a GitHub Release.
|
||||||
|
- Docker: as tags versionadas e `latest` passam a ser publicadas exclusivamente por releases oficiais, depois das verificações de qualidade.
|
||||||
|
|
||||||
|
## [2.7.8] - 2026-06-21
|
||||||
|
|
||||||
|
Esta versão deixa documentos e comprovantes mais fáceis de guardar e encontrar sem tirar o foco da rotina financeira. Agora é possível manter arquivos junto às notas, consultar a galeria por pessoa com identificação visual e abrir uma categoria diretamente das tendências do dashboard, sempre preservando o contexto do período selecionado.
|
||||||
|
|
||||||
|
### Adicionado
|
||||||
|
- Anotações: itens do tipo `Nota` agora aceitam anexos PDF, JPEG, PNG e WebP na criação e na edição, com consulta e download nos detalhes e respeito ao limite configurado pelo usuário.
|
||||||
|
- Anexos: a galeria agora oferece filtro por pessoa, incluindo a pessoa principal, pessoas específicas e uma visão consolidada de todas as pessoas.
|
||||||
|
|
||||||
|
### Alterado
|
||||||
|
- Anexos: os cards da galeria agora identificam a pessoa vinculada ao lançamento e o filtro exibe os respectivos avatares, preservando o contexto quando vários responsáveis são exibidos.
|
||||||
|
- Dashboard: os nomes no widget `Tendências de categorias` agora levam aos detalhes da categoria mantendo o período selecionado.
|
||||||
|
|
||||||
|
## [2.7.7] - 2026-06-20
|
||||||
|
|
||||||
|
Esta versão faz ajustes pontuais de leitura nos resumos financeiros e no dashboard, reforçando a identidade visual de cartões e contas e deixando as listas dos widgets mais consistentes sem alterar a estrutura de navegação das páginas.
|
||||||
|
|
||||||
|
### Alterado
|
||||||
|
- Cartões e contas: os cabeçalhos dos resumos agora destacam melhor o logo, o nome da entidade e o período exibido.
|
||||||
|
- Dashboard: as listas dos widgets agora compartilham padrões de altura, espaçamento, alinhamento e truncamento para melhorar a leitura de valores, status e metadados.
|
||||||
|
|
||||||
|
## [2.7.6] - 2026-06-20
|
||||||
|
|
||||||
|
Esta versão melhora dois fluxos importantes: a importação de planilhas fica mais esperta ao reconhecer categorias já informadas no arquivo, e lançamentos avulsos podem ser reorganizados como parcelamentos ou recorrências sem precisar recriá-los manualmente.
|
||||||
|
|
||||||
|
As funcionalidades desta versão foram desenvolvidas originalmente por Yuri Argolo (`yurnasg`) e adaptadas para integração ao projeto principal.
|
||||||
|
|
||||||
|
### Adicionado
|
||||||
|
- Importação: planilhas XLS/XLSX agora aceitam a coluna `Categoria` no template e tentam mapear automaticamente o valor para uma categoria existente compatível com o tipo do lançamento.
|
||||||
|
- Lançamentos: lançamentos à vista agora podem ser convertidos em recorrentes diretamente pelo menu de ações.
|
||||||
|
- Lançamentos: lançamentos à vista de cartão de crédito agora podem ser convertidos em uma série parcelada informando o total de parcelas.
|
||||||
|
|
||||||
|
### Alterado
|
||||||
|
- Lançamentos: conversões para séries respeitam faturas pagas e limite disponível do cartão antes de criar novos movimentos.
|
||||||
|
|
||||||
|
## [2.7.5] - 2026-06-13
|
||||||
|
|
||||||
|
Esta versão faz um polimento pontual no dashboard, deixando os widgets mais explicativos, consistentes e confiáveis quando há listas maiores ou informações complementares para revisar.
|
||||||
|
|
||||||
|
### Alterado
|
||||||
|
- Dashboard: os indicadores percentuais de faturas por pessoa, despesas por categoria, receitas por categoria e tendências de categorias agora deixam explícito que a comparação é contra o mês anterior.
|
||||||
|
- Dashboard: pequenos ajustes visuais em widgets melhoram espaçamento, bordas e leitura de itens financeiros.
|
||||||
|
|
||||||
|
### Corrigido
|
||||||
|
- Dashboard: o widget `Lançamentos por categoria` agora recalcula corretamente o overflow quando a lista muda e volta a exibir o botão `Expandir` em listagens grandes.
|
||||||
|
- Relatórios: em `/reports/installment-analysis`, os cards de parcelamentos agora exibem o ícone de observação ao lado do nome do lançamento quando há anotação cadastrada.
|
||||||
|
|
||||||
|
## [2.7.4] - 2026-06-09
|
||||||
|
|
||||||
|
Esta versão corrige o fluxo de revisão de lançamentos compartilhados para que o acesso somente leitura proteja os dados originais sem impedir que a pessoa copie movimentos para a própria conta.
|
||||||
|
|
||||||
|
### Corrigido
|
||||||
|
- Pessoas: lançamentos de uma pessoa compartilhada em modo somente leitura agora podem ser selecionados e importados para a conta do usuário logado, tanto individualmente quanto em lote, mantendo edição e remoção bloqueadas no lançamento original.
|
||||||
|
|
||||||
|
## [2.7.3] - 2026-06-05
|
||||||
|
|
||||||
|
Esta versão melhora pequenos pontos de leitura e configuração para o uso diário e self-hosted. As faturas pagas ficam mais fáceis de identificar na lista de cartões, a configuração de origins confiáveis do Better Auth passa a ficar documentada para Docker e túneis, o dashboard corrige a leitura de tempo dos pré-lançamentos e as dependências seguem atualizadas sem quebrar o build da imagem.
|
||||||
|
|
||||||
|
### Adicionado
|
||||||
|
- Cartões: a lista de cartões agora exibe a etiqueta `Paga` ao lado do valor da fatura atual quando ela já foi quitada.
|
||||||
|
- Self-hosting: adicionada a variável `BETTER_AUTH_TRUSTED_ORIGINS` ao `.env.example`, ao `docker-compose.yml` e ao README para permitir origins adicionais confiáveis em cenários com Cloudflare Tunnel, reverse proxy ou URLs diferentes de `BETTER_AUTH_URL`.
|
||||||
|
|
||||||
|
### Alterado
|
||||||
|
- Dependências: atualizados Next.js, React, Better Auth, AI SDK, AWS SDK, pdf.js e ferramentas de desenvolvimento usadas no build.
|
||||||
|
|
||||||
|
### Corrigido
|
||||||
|
- Dashboard: o widget `Pré-lançamentos` agora calcula o rótulo `há X` a partir da chegada do item ao OpenMonetis, evitando deslocamentos causados por timestamps de notificação enviados com timezone incorreto.
|
||||||
|
- Anexos: o preview de PDFs foi ajustado para a API atual do `pdfjs-dist`, evitando falha de TypeScript durante o build da imagem Docker.
|
||||||
|
|
||||||
## [2.7.2] - 2026-05-31
|
## [2.7.2] - 2026-05-31
|
||||||
|
|
||||||
Esta versão atualiza as imagens de apresentação do OpenMonetis na landing page e no compartilhamento em redes sociais.
|
Esta versão atualiza as imagens de apresentação do OpenMonetis na landing page e no compartilhamento em redes sociais.
|
||||||
|
|||||||
41
README.md
@@ -6,9 +6,11 @@
|
|||||||
Projeto pessoal de gestão financeira. Self-hosted, manual e open source.
|
Projeto pessoal de gestão financeira. Self-hosted, manual e open source.
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
> **⚠️ Não há versão online hospedada.** Você precisa clonar o repositório e rodar localmente ou no seu próprio servidor.
|
> **⚠️ Nota:** o OpenMonetis não está sendo encerrado, mas o desenvolvimento deve reduzir para quase zero daqui em diante. O app já cobre minhas demandas atuais de gerenciamento financeiro, então novas mudanças tendem a ser pontuais: correções, ajustes necessários e pequenas melhorias quando fizerem bastante sentido para meu uso.
|
||||||
|
|
||||||
[](CHANGELOG.md)
|
> **Não há versão online hospedada.** Você precisa clonar o repositório e rodar localmente ou no seu próprio servidor.
|
||||||
|
|
||||||
|
[](CHANGELOG.md)
|
||||||
[](https://nextjs.org/)
|
[](https://nextjs.org/)
|
||||||
[](https://www.typescriptlang.org/)
|
[](https://www.typescriptlang.org/)
|
||||||
[](https://www.postgresql.org/)
|
[](https://www.postgresql.org/)
|
||||||
@@ -63,11 +65,11 @@ 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 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, 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.
|
||||||
|
|
||||||
💳 **Faturas de cartão** — Acompanhe faturas por período, controle limites e vencimentos.
|
💳 **Faturas de cartão** — Acompanhe faturas por período, controle limites e vencimentos com identificação visual mais clara do cartão.
|
||||||
|
|
||||||
🎯 **Orçamentos** — Defina limites por categoria e acompanhe o progresso.
|
🎯 **Orçamentos** — Defina limites por categoria e acompanhe o progresso.
|
||||||
|
|
||||||
@@ -77,7 +79,7 @@ A ideia é simples: ter um lugar onde consigo ver todas as minhas contas, cartõ
|
|||||||
|
|
||||||
👥 **Gestão colaborativa** — Pagadores com permissões (admin/viewer), notificações automáticas por e-mail, códigos de compartilhamento.
|
👥 **Gestão colaborativa** — Pagadores com permissões (admin/viewer), notificações automáticas por e-mail, códigos de compartilhamento.
|
||||||
|
|
||||||
📝 **Anotações e tarefas** — Notas de texto, listas com checkboxes, sistema de arquivamento.
|
📝 **Anotações e tarefas** — Notas de texto com anexos, listas com checkboxes e sistema de arquivamento.
|
||||||
|
|
||||||
📅 **Calendário financeiro** — Visualize todos os lançamentos em um calendário mensal.
|
📅 **Calendário financeiro** — Visualize todos os lançamentos em um calendário mensal.
|
||||||
|
|
||||||
@@ -87,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
|
||||||
|
|
||||||
@@ -451,6 +453,7 @@ POSTGRES_DB=openmonetis_db
|
|||||||
DISABLE_SIGNUP=false # true bloqueia novos cadastros
|
DISABLE_SIGNUP=false # true bloqueia novos cadastros
|
||||||
AUTH_SESSION_EXPIRES_IN_DAYS=30 # duração de sessões persistentes
|
AUTH_SESSION_EXPIRES_IN_DAYS=30 # duração de sessões persistentes
|
||||||
AUTH_SESSION_UPDATE_AGE_HOURS=24 # frequência de renovação da sessão
|
AUTH_SESSION_UPDATE_AGE_HOURS=24 # frequência de renovação da sessão
|
||||||
|
BETTER_AUTH_TRUSTED_ORIGINS= # origins adicionais confiáveis, separadas por vírgula
|
||||||
|
|
||||||
# S3 Server (opcional, necessario para anexos)
|
# S3 Server (opcional, necessario para anexos)
|
||||||
S3_ENDPOINT=
|
S3_ENDPOINT=
|
||||||
@@ -485,6 +488,19 @@ LOGO_DEV_TOKEN=
|
|||||||
LOGO_DEV_SECRET_KEY=
|
LOGO_DEV_SECRET_KEY=
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### BETTER_AUTH_TRUSTED_ORIGINS
|
||||||
|
|
||||||
|
Use `BETTER_AUTH_TRUSTED_ORIGINS` quando o OpenMonetis for acessado por uma URL diferente de `BETTER_AUTH_URL`, como Cloudflare Tunnel, reverse proxy, domínio local ou subdomínios temporários. Isso evita falhas de login como `Invalid origin` sem precisar alterar a imagem Docker.
|
||||||
|
|
||||||
|
Informe apenas origins confiáveis, separadas por vírgula:
|
||||||
|
|
||||||
|
```env
|
||||||
|
BETTER_AUTH_URL=http://localhost:3000
|
||||||
|
BETTER_AUTH_TRUSTED_ORIGINS=https://*.trycloudflare.com,https://openmonetis.seudominio.com
|
||||||
|
```
|
||||||
|
|
||||||
|
Para Google OAuth e outros callbacks externos, mantenha `BETTER_AUTH_URL` apontando para a URL pública/canônica configurada no provedor.
|
||||||
|
|
||||||
### IA local com Ollama
|
### IA local com Ollama
|
||||||
|
|
||||||
O provider Ollama permite gerar insights usando modelos locais. Instale e suba o Ollama no host onde o modelo ficará disponível:
|
O provider Ollama permite gerar insights usando modelos locais. Instale e suba o Ollama no host onde o modelo ficará disponível:
|
||||||
@@ -607,6 +623,17 @@ A regra é: `actions.ts` e `queries.ts` são as portas de entrada da feature. Tu
|
|||||||
|
|
||||||
Antes de começar, leia o [`CLAUDE.md`](CLAUDE.md) — ele documenta a arquitetura, convenções de nomenclatura, regras de queries e o checklist para novas features. Use TypeScript, commits semânticos e mantenha o `CHANGELOG.md` atualizado.
|
Antes de começar, leia o [`CLAUDE.md`](CLAUDE.md) — ele documenta a arquitetura, convenções de nomenclatura, regras de queries e o checklist para novas features. Use TypeScript, commits semânticos e mantenha o `CHANGELOG.md` atualizado.
|
||||||
|
|
||||||
|
### Publicando uma versão
|
||||||
|
|
||||||
|
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
|
||||||
|
git tag -a v2.7.13 -m "v2.7.13"
|
||||||
|
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.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 💖 Apoie o Projeto
|
## 💖 Apoie o Projeto
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://biomejs.dev/schemas/2.4.15/schema.json",
|
"$schema": "https://biomejs.dev/schemas/2.4.16/schema.json",
|
||||||
"vcs": {
|
"vcs": {
|
||||||
"enabled": true,
|
"enabled": true,
|
||||||
"clientKind": "git",
|
"clientKind": "git",
|
||||||
|
|||||||
@@ -36,6 +36,7 @@ services:
|
|||||||
DATABASE_URL: ${DATABASE_URL:-postgresql://openmonetis:openmonetis_dev_password@db:5432/openmonetis_db}
|
DATABASE_URL: ${DATABASE_URL:-postgresql://openmonetis:openmonetis_dev_password@db:5432/openmonetis_db}
|
||||||
BETTER_AUTH_SECRET: ${BETTER_AUTH_SECRET:-}
|
BETTER_AUTH_SECRET: ${BETTER_AUTH_SECRET:-}
|
||||||
BETTER_AUTH_URL: ${BETTER_AUTH_URL:-http://localhost:3000}
|
BETTER_AUTH_URL: ${BETTER_AUTH_URL:-http://localhost:3000}
|
||||||
|
BETTER_AUTH_TRUSTED_ORIGINS: ${BETTER_AUTH_TRUSTED_ORIGINS:-}
|
||||||
depends_on:
|
depends_on:
|
||||||
db:
|
db:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
|
|||||||
9
drizzle/0031_lame_cerise.sql
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
CREATE TABLE "anotacao_anexos" (
|
||||||
|
"anotacao_id" uuid NOT NULL,
|
||||||
|
"anexo_id" uuid NOT NULL,
|
||||||
|
CONSTRAINT "anotacao_anexos_anotacao_id_anexo_id_pk" PRIMARY KEY("anotacao_id","anexo_id")
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
ALTER TABLE "anotacao_anexos" ADD CONSTRAINT "anotacao_anexos_anotacao_id_anotacoes_id_fk" FOREIGN KEY ("anotacao_id") REFERENCES "public"."anotacoes"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "anotacao_anexos" ADD CONSTRAINT "anotacao_anexos_anexo_id_anexos_id_fk" FOREIGN KEY ("anexo_id") REFERENCES "public"."anexos"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
CREATE INDEX "anotacao_anexos_anexo_id_idx" ON "anotacao_anexos" USING btree ("anexo_id");
|
||||||
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
@@ -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
@@ -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;
|
||||||
2988
drizzle/meta/0031_snapshot.json
Normal file
2995
drizzle/meta/0032_snapshot.json
Normal file
3002
drizzle/meta/0033_snapshot.json
Normal file
3008
drizzle/meta/0034_snapshot.json
Normal file
@@ -211,6 +211,34 @@
|
|||||||
"when": 1780150535055,
|
"when": 1780150535055,
|
||||||
"tag": "0030_complete_umar",
|
"tag": "0030_complete_umar",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 31,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1782051007412,
|
||||||
|
"tag": "0031_lame_cerise",
|
||||||
|
"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"],
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|||||||
60
package.json
@@ -1,10 +1,10 @@
|
|||||||
{
|
{
|
||||||
"name": "openmonetis",
|
"name": "openmonetis",
|
||||||
"version": "2.7.2",
|
"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.79",
|
"@ai-sdk/anthropic": "^3.0.88",
|
||||||
"@ai-sdk/google": "^3.0.79",
|
"@ai-sdk/google": "^3.0.85",
|
||||||
"@ai-sdk/openai": "^3.0.65",
|
"@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.1050.0",
|
"@aws-sdk/client-s3": "^3.1075.0",
|
||||||
"@aws-sdk/s3-request-presigner": "^3.1050.0",
|
"@aws-sdk/s3-request-presigner": "^3.1075.0",
|
||||||
"@better-auth/passkey": "^1.6.11",
|
"@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,29 +64,29 @@
|
|||||||
"@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.100.14",
|
"@tanstack/react-query": "^5.101.1",
|
||||||
"@tanstack/react-table": "8.21.3",
|
"@tanstack/react-table": "8.21.3",
|
||||||
"@tanstack/react-virtual": "^3.13.26",
|
"@tanstack/react-virtual": "^3.14.4",
|
||||||
"ai": "^6.0.191",
|
"ai": "^6.0.213",
|
||||||
"better-auth": "1.6.11",
|
"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",
|
||||||
"cmdk": "^1.1.1",
|
"cmdk": "^1.1.1",
|
||||||
"date-fns": "^4.3.0",
|
"date-fns": "^4.4.0",
|
||||||
"drizzle-orm": "0.45.2",
|
"drizzle-orm": "0.45.2",
|
||||||
"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.6",
|
"next": "16.3.0",
|
||||||
"next-themes": "0.4.6",
|
"next-themes": "0.4.6",
|
||||||
"pdfjs-dist": "^5.7.284",
|
"pdfjs-dist": "^6.0.227",
|
||||||
"pg": "8.21.0",
|
"pg": "8.21.0",
|
||||||
"react": "19.2.6",
|
"react": "19.2.7",
|
||||||
"react-day-picker": "^10.0.1",
|
"react-day-picker": "^10.0.1",
|
||||||
"react-dom": "19.2.6",
|
"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",
|
||||||
@@ -95,19 +95,19 @@
|
|||||||
"zod": "4.4.3"
|
"zod": "4.4.3"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@biomejs/biome": "2.4.15",
|
"@biomejs/biome": "2.4.16",
|
||||||
"@tailwindcss/postcss": "4.3.0",
|
"@tailwindcss/postcss": "4.3.0",
|
||||||
"@types/canvas-confetti": "^1.9.0",
|
"@types/canvas-confetti": "^1.9.0",
|
||||||
"@types/node": "25.9.1",
|
"@types/node": "25.9.1",
|
||||||
"@types/pg": "^8.20.0",
|
"@types/pg": "^8.20.0",
|
||||||
"@types/react": "19.2.15",
|
"@types/react": "19.2.16",
|
||||||
"@types/react-dom": "19.2.3",
|
"@types/react-dom": "19.2.3",
|
||||||
"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.14.2",
|
"knip": "^6.22.0",
|
||||||
"tailwindcss": "4.3.0",
|
"tailwindcss": "4.3.0",
|
||||||
"tsx": "4.22.3",
|
"tsx": "4.22.4",
|
||||||
"typescript": "6.0.3"
|
"typescript": "7.0.2"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
4448
pnpm-lock.yaml
generated
@@ -7,29 +7,7 @@ allowBuilds:
|
|||||||
sharp: true
|
sharp: true
|
||||||
unrs-resolver: true
|
unrs-resolver: true
|
||||||
|
|
||||||
minimumReleaseAgeExclude:
|
minimumReleaseAge: 0
|
||||||
- '@aws-sdk/client-s3@3.1050.0'
|
|
||||||
- '@aws-sdk/s3-request-presigner@3.1050.0'
|
|
||||||
- '@types/node@25.9.1'
|
|
||||||
- '@types/react@19.2.15'
|
|
||||||
- '@aws-sdk/client-s3@3.1054.0'
|
|
||||||
- '@aws-sdk/core@3.974.14'
|
|
||||||
- '@aws-sdk/credential-provider-env@3.972.40'
|
|
||||||
- '@aws-sdk/credential-provider-http@3.972.42'
|
|
||||||
- '@aws-sdk/credential-provider-ini@3.972.44'
|
|
||||||
- '@aws-sdk/credential-provider-login@3.972.44'
|
|
||||||
- '@aws-sdk/credential-provider-node@3.972.45'
|
|
||||||
- '@aws-sdk/credential-provider-process@3.972.40'
|
|
||||||
- '@aws-sdk/credential-provider-sso@3.972.44'
|
|
||||||
- '@aws-sdk/credential-provider-web-identity@3.972.44'
|
|
||||||
- '@aws-sdk/middleware-bucket-endpoint@3.972.16'
|
|
||||||
- '@aws-sdk/middleware-flexible-checksums@3.974.22'
|
|
||||||
- '@aws-sdk/middleware-sdk-s3@3.972.43'
|
|
||||||
- '@aws-sdk/nested-clients@3.997.12'
|
|
||||||
- '@aws-sdk/s3-request-presigner@3.1054.0'
|
|
||||||
- '@aws-sdk/signature-v4-multi-region@3.996.29'
|
|
||||||
- '@aws-sdk/token-providers@3.1054.0'
|
|
||||||
- '@aws-sdk/xml-builder@3.972.26'
|
|
||||||
|
|
||||||
overrides:
|
overrides:
|
||||||
defu: 6.1.7
|
defu: 6.1.7
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 5.4 KiB After Width: | Height: | Size: 3.4 KiB |
|
Before Width: | Height: | Size: 598 KiB After Width: | Height: | Size: 350 KiB |
|
Before Width: | Height: | Size: 589 KiB After Width: | Height: | Size: 355 KiB |
@@ -1,3 +1 @@
|
|||||||
<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200" viewBox="0 0 200 200" role="img" aria-label="OpenMonetis">
|
<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200" aria-label="OpenMonetis" role="img" viewBox="0 0 200 200"><path fill="#f73" d="M 77.66,165.64 L 37.77,141.54 L 63.30,108.72 L 27.13,97.44 L 46.81,50.77 L 77.66,63.08 L 81.91,30.26 L 126.40,29.23 L 126.06,33.85 L 122.87,67.69 L 158.51,50.77 L 178.19,90.26 L 140.96,104.62 L 162.23,127.18 L 132.98,162.56 L 103.19,131.79 Z"/></svg>
|
||||||
<path fill="#ff7733" d="M 77.66,165.64 L 37.77,141.54 L 63.30,108.72 L 27.13,97.44 L 46.81,50.77 L 77.66,63.08 L 81.91,30.26 L 126.40,29.23 L 126.06,33.85 L 122.87,67.69 L 158.51,50.77 L 178.19,90.26 L 140.96,104.62 L 162.23,127.18 L 132.98,162.56 L 103.19,131.79 Z"/>
|
|
||||||
</svg>
|
|
||||||
|
Before Width: | Height: | Size: 402 B After Width: | Height: | Size: 394 B |
|
Before Width: | Height: | Size: 6.7 KiB After Width: | Height: | Size: 6.7 KiB |
|
Before Width: | Height: | Size: 182 KiB After Width: | Height: | Size: 139 KiB |
|
Before Width: | Height: | Size: 177 KiB After Width: | Height: | Size: 137 KiB |
|
Before Width: | Height: | Size: 48 KiB After Width: | Height: | Size: 34 KiB |
|
Before Width: | Height: | Size: 72 KiB After Width: | Height: | Size: 17 KiB |
@@ -1 +1 @@
|
|||||||
<svg height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>MiniMax</title><defs><linearGradient id="lobe-icons-minimax-gradient" x1="0%" x2="100.182%" y1="50.057%" y2="50.057%"><stop offset="0%" stop-color="#E2167E"/><stop offset="100%" stop-color="#FE603C"/></linearGradient></defs><path d="M16.278 2c1.156 0 2.093.927 2.093 2.07v12.501a.74.74 0 00.744.709.74.74 0 00.743-.709V9.099a2.06 2.06 0 012.071-2.049A2.06 2.06 0 0124 9.1v6.561a.649.649 0 01-.652.645.649.649 0 01-.653-.645V9.1a.762.762 0 00-.766-.758.762.762 0 00-.766.758v7.472a2.037 2.037 0 01-2.048 2.026 2.037 2.037 0 01-2.048-2.026v-12.5a.785.785 0 00-.788-.753.785.785 0 00-.789.752l-.001 15.904A2.037 2.037 0 0113.441 22a2.037 2.037 0 01-2.048-2.026V18.04c0-.356.292-.645.652-.645.36 0 .652.289.652.645v1.934c0 .263.142.506.372.638.23.131.514.131.744 0a.734.734 0 00.372-.638V4.07c0-1.143.937-2.07 2.093-2.07zm-5.674 0c1.156 0 2.093.927 2.093 2.07v11.523a.648.648 0 01-.652.645.648.648 0 01-.652-.645V4.07a.785.785 0 00-.789-.78.785.785 0 00-.789.78v14.013a2.06 2.06 0 01-2.07 2.048 2.06 2.06 0 01-2.071-2.048V9.1a.762.762 0 00-.766-.758.762.762 0 00-.766.758v3.8a2.06 2.06 0 01-2.071 2.049A2.06 2.06 0 010 12.9v-1.378c0-.357.292-.646.652-.646.36 0 .653.29.653.646V12.9c0 .418.343.757.766.757s.766-.339.766-.757V9.099a2.06 2.06 0 012.07-2.048 2.06 2.06 0 012.071 2.048v8.984c0 .419.343.758.767.758.423 0 .766-.339.766-.758V4.07c0-1.143.937-2.07 2.093-2.07z" fill="url(#lobe-icons-minimax-gradient)" fill-rule="nonzero"/></svg>
|
<svg xmlns="http://www.w3.org/2000/svg" height="1em" style="flex:none;line-height:1" width="1em" viewBox="0 0 24 24"><title>MiniMax</title><defs><linearGradient id="lobe-icons-minimax-gradient" x1="0%" x2="100.182%" y1="50.057%" y2="50.057%"><stop offset="0%" stop-color="#E2167E"/><stop offset="100%" stop-color="#FE603C"/></linearGradient></defs><path fill="url(#lobe-icons-minimax-gradient)" fill-rule="nonzero" d="M16.278 2c1.156 0 2.093.927 2.093 2.07v12.501a.74.74 0 00.744.709.74.74 0 00.743-.709V9.099a2.06 2.06 0 012.071-2.049A2.06 2.06 0 0124 9.1v6.561a.649.649 0 01-.652.645.649.649 0 01-.653-.645V9.1a.762.762 0 00-.766-.758.762.762 0 00-.766.758v7.472a2.037 2.037 0 01-2.048 2.026 2.037 2.037 0 01-2.048-2.026v-12.5a.785.785 0 00-.788-.753.785.785 0 00-.789.752l-.001 15.904A2.037 2.037 0 0113.441 22a2.037 2.037 0 01-2.048-2.026V18.04c0-.356.292-.645.652-.645.36 0 .652.289.652.645v1.934c0 .263.142.506.372.638.23.131.514.131.744 0a.734.734 0 00.372-.638V4.07c0-1.143.937-2.07 2.093-2.07zm-5.674 0c1.156 0 2.093.927 2.093 2.07v11.523a.648.648 0 01-.652.645.648.648 0 01-.652-.645V4.07a.785.785 0 00-.789-.78.785.785 0 00-.789.78v14.013a2.06 2.06 0 01-2.07 2.048 2.06 2.06 0 01-2.071-2.048V9.1a.762.762 0 00-.766-.758.762.762 0 00-.766.758v3.8a2.06 2.06 0 01-2.071 2.049A2.06 2.06 0 010 12.9v-1.378c0-.357.292-.646.652-.646.36 0 .653.29.653.646V12.9c0 .418.343.757.766.757s.766-.339.766-.757V9.099a2.06 2.06 0 012.07-2.048 2.06 2.06 0 012.071 2.048v8.984c0 .419.343.758.767.758.423 0 .766-.339.766-.758V4.07c0-1.143.937-2.07 2.093-2.07z"/></svg>
|
||||||
|
Before Width: | Height: | Size: 1.5 KiB After Width: | Height: | Size: 1.5 KiB |
|
Before Width: | Height: | Size: 8.4 KiB After Width: | Height: | Size: 8.4 KiB |
|
Before Width: | Height: | Size: 8.4 KiB After Width: | Height: | Size: 8.4 KiB |
@@ -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 { fetchAttachmentsForPeriod } 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,18 +20,32 @@ 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;
|
||||||
const periodoParam = getSingleParam(resolvedSearchParams, "periodo");
|
const periodoParam = getSingleParam(resolvedSearchParams, "periodo");
|
||||||
const { period } = parsePeriodParam(periodoParam);
|
const { period } = parsePeriodParam(periodoParam);
|
||||||
|
|
||||||
const attachments = await fetchAttachmentsForPeriod(userId, period);
|
const data = await fetchAttachmentsPageData(userId, period);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="flex flex-col gap-6">
|
<main className="flex flex-col gap-6">
|
||||||
<AttachmentsPage attachments={attachments} />
|
<AttachmentsPage
|
||||||
|
attachments={data?.attachments ?? []}
|
||||||
|
adminPayerId={data?.adminPayerId ?? ""}
|
||||||
|
/>
|
||||||
</main>
|
</main>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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);
|
||||||
@@ -136,6 +138,7 @@ export default async function Page({ params, searchParams }: PageProps) {
|
|||||||
limitAvailable: limitAmount,
|
limitAvailable: limitAmount,
|
||||||
currentInvoiceAmount: 0,
|
currentInvoiceAmount: 0,
|
||||||
currentInvoiceLabel: "",
|
currentInvoiceLabel: "",
|
||||||
|
currentInvoiceStatus: null,
|
||||||
};
|
};
|
||||||
|
|
||||||
const { totalAmount, invoiceStatus, paymentDate } = invoiceData;
|
const { totalAmount, invoiceStatus, paymentDate } = invoiceData;
|
||||||
@@ -209,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");
|
||||||
|
|||||||
@@ -1,16 +1,24 @@
|
|||||||
import { connection } from "next/server";
|
import { connection } from "next/server";
|
||||||
import { NotesPage } from "@/features/notes/components/notes-page";
|
import { NotesPage } from "@/features/notes/components/notes-page";
|
||||||
import { fetchAllNotesForUser } from "@/features/notes/queries";
|
import { fetchAllNotesForUser } from "@/features/notes/queries";
|
||||||
|
import { fetchUserPreferences } from "@/features/settings/queries";
|
||||||
import { getUserId } from "@/shared/lib/auth/server";
|
import { getUserId } from "@/shared/lib/auth/server";
|
||||||
|
|
||||||
export default async function Page() {
|
export default async function Page() {
|
||||||
await connection();
|
await connection();
|
||||||
const userId = await getUserId();
|
const userId = await getUserId();
|
||||||
const { activeNotes, archivedNotes } = await fetchAllNotesForUser(userId);
|
const [{ activeNotes, archivedNotes }, preferences] = await Promise.all([
|
||||||
|
fetchAllNotesForUser(userId),
|
||||||
|
fetchUserPreferences(userId),
|
||||||
|
]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="flex flex-col gap-6">
|
<main className="flex flex-col gap-6">
|
||||||
<NotesPage notes={activeNotes} archivedNotes={archivedNotes} />
|
<NotesPage
|
||||||
|
notes={activeNotes}
|
||||||
|
archivedNotes={archivedNotes}
|
||||||
|
attachmentMaxSizeMb={preferences?.attachmentMaxSizeMb ?? 50}
|
||||||
|
/>
|
||||||
</main>
|
</main>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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" />
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
@custom-variant dark (&:is(.dark *));
|
@custom-variant dark (&:is(.dark *));
|
||||||
|
|
||||||
@theme {
|
@theme {
|
||||||
--spacing-custom-height-card: 29rem;
|
--spacing-custom-height-card: 30rem;
|
||||||
--spacing-8xl: 90rem;
|
--spacing-8xl: 90rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -117,7 +117,7 @@
|
|||||||
--destructive: oklch(62% 0.2 28);
|
--destructive: oklch(62% 0.2 28);
|
||||||
--destructive-foreground: oklch(98% 0.005 30);
|
--destructive-foreground: oklch(98% 0.005 30);
|
||||||
|
|
||||||
--border: oklch(24.576% 0.0072 67.399);
|
--border: oklch(29.675% 0.01144 67.3);
|
||||||
--input: var(--border);
|
--input: var(--border);
|
||||||
--ring: var(--primary);
|
--ring: var(--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`),
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -847,11 +856,12 @@ export const budgetsRelations = relations(budgets, ({ one }) => ({
|
|||||||
}),
|
}),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
export const notesRelations = relations(notes, ({ one }) => ({
|
export const notesRelations = relations(notes, ({ one, many }) => ({
|
||||||
user: one(user, {
|
user: one(user, {
|
||||||
fields: [notes.userId],
|
fields: [notes.userId],
|
||||||
references: [user.id],
|
references: [user.id],
|
||||||
}),
|
}),
|
||||||
|
noteAttachments: many(noteAttachments),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
export const savedInsightsRelations = relations(savedInsights, ({ one }) => ({
|
export const savedInsightsRelations = relations(savedInsights, ({ one }) => ({
|
||||||
@@ -972,6 +982,24 @@ export const transactionAttachments = pgTable(
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
export const noteAttachments = pgTable(
|
||||||
|
"anotacao_anexos",
|
||||||
|
{
|
||||||
|
noteId: uuid("anotacao_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => notes.id, { onDelete: "cascade" }),
|
||||||
|
attachmentId: uuid("anexo_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => attachments.id, { onDelete: "cascade" }),
|
||||||
|
},
|
||||||
|
(table) => ({
|
||||||
|
pk: primaryKey({ columns: [table.noteId, table.attachmentId] }),
|
||||||
|
attachmentIdIdx: index("anotacao_anexos_anexo_id_idx").on(
|
||||||
|
table.attachmentId,
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
export const importCategoryMappings = pgTable(
|
export const importCategoryMappings = pgTable(
|
||||||
"import_category_mappings",
|
"import_category_mappings",
|
||||||
{
|
{
|
||||||
@@ -1044,6 +1072,7 @@ export const attachmentsRelations = relations(attachments, ({ one, many }) => ({
|
|||||||
references: [user.id],
|
references: [user.id],
|
||||||
}),
|
}),
|
||||||
transactionAttachments: many(transactionAttachments),
|
transactionAttachments: many(transactionAttachments),
|
||||||
|
noteAttachments: many(noteAttachments),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
export const transactionAttachmentsRelations = relations(
|
export const transactionAttachmentsRelations = relations(
|
||||||
@@ -1060,8 +1089,23 @@ export const transactionAttachmentsRelations = relations(
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
export const noteAttachmentsRelations = relations(
|
||||||
|
noteAttachments,
|
||||||
|
({ one }) => ({
|
||||||
|
note: one(notes, {
|
||||||
|
fields: [noteAttachments.noteId],
|
||||||
|
references: [notes.id],
|
||||||
|
}),
|
||||||
|
attachment: one(attachments, {
|
||||||
|
fields: [noteAttachments.attachmentId],
|
||||||
|
references: [attachments.id],
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
export type Attachment = typeof attachments.$inferSelect;
|
export type Attachment = typeof attachments.$inferSelect;
|
||||||
export type TransactionAttachment = typeof transactionAttachments.$inferSelect;
|
export type TransactionAttachment = typeof transactionAttachments.$inferSelect;
|
||||||
|
export type NoteAttachment = typeof noteAttachments.$inferSelect;
|
||||||
|
|
||||||
export const establishmentLogosRelations = relations(
|
export const establishmentLogosRelations = relations(
|
||||||
establishmentLogos,
|
establishmentLogos,
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { RiInformationLine } from "@remixicon/react";
|
import { RiBankLine, RiInformationLine } from "@remixicon/react";
|
||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
import type { ReactNode } from "react";
|
import type { ReactNode } from "react";
|
||||||
import MoneyValues from "@/shared/components/money-values";
|
import MoneyValues from "@/shared/components/money-values";
|
||||||
@@ -52,28 +52,32 @@ export function AccountStatementCard({
|
|||||||
const resultado = totalIncomes - totalExpenses;
|
const resultado = totalIncomes - totalExpenses;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card className="gap-0 py-0">
|
<Card className="gap-0 py-0 space-y-2">
|
||||||
<CardContent className="px-4 py-4 sm:px-5 sm:py-5">
|
<CardContent className="px-4 py-4 sm:px-5 sm:py-5">
|
||||||
<div className="flex flex-col gap-4">
|
<div className="flex flex-col gap-4">
|
||||||
{/* Linha 1 — identidade */}
|
{/* Linha 1 — identidade */}
|
||||||
<div className="flex items-center justify-between gap-3">
|
<div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
|
||||||
<div className="flex min-w-0 items-center gap-3">
|
<div className="flex min-w-0 items-start gap-3">
|
||||||
{logoPath ? (
|
{logoPath ? (
|
||||||
<div className="flex size-12 shrink-0 items-center justify-center overflow-hidden rounded-full">
|
<div className="flex size-12 shrink-0 items-center justify-center overflow-hidden rounded-full">
|
||||||
<Image
|
<Image
|
||||||
src={logoPath}
|
src={logoPath}
|
||||||
alt={`Logo ${accountName}`}
|
alt={`Logo ${accountName}`}
|
||||||
width={42}
|
width={48}
|
||||||
height={42}
|
height={48}
|
||||||
className="h-full w-full object-contain"
|
className="h-full w-full object-contain"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : (
|
||||||
<div className="min-w-0">
|
<span className="flex size-12 shrink-0 items-center justify-center rounded-full border bg-card text-primary">
|
||||||
<h2 className="truncate text-sm font-semibold text-foreground">
|
<RiBankLine className="size-5" aria-hidden />
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
<div className="min-w-0 space-y-1">
|
||||||
|
<h2 className="truncate text-xl font-semibold text-foreground sm:text-2xl">
|
||||||
{accountName}
|
{accountName}
|
||||||
</h2>
|
</h2>
|
||||||
<p className="text-xs text-muted-foreground">
|
<p className="text-sm leading-relaxed text-muted-foreground">
|
||||||
Extrato de {periodLabel}
|
Extrato de {periodLabel}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ function PdfCanvas({ url }: PdfCanvasProps) {
|
|||||||
|
|
||||||
let pdf: Awaited<ReturnType<typeof pdfjsLib.getDocument>["promise"]>;
|
let pdf: Awaited<ReturnType<typeof pdfjsLib.getDocument>["promise"]>;
|
||||||
try {
|
try {
|
||||||
pdf = await pdfjsLib.getDocument(url).promise;
|
pdf = await pdfjsLib.getDocument({ url }).promise;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if ((err as { name?: string }).name === "PasswordException") {
|
if ((err as { name?: string }).name === "PasswordException") {
|
||||||
if (!cancelled) setLocked(true);
|
if (!cancelled) setLocked(true);
|
||||||
@@ -162,9 +162,15 @@ export function AttachmentGridItem({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Data */}
|
{/* Data */}
|
||||||
<span className="text-xs text-muted-foreground">
|
<div className="flex min-w-0 items-center gap-1 text-xs text-muted-foreground">
|
||||||
|
<span className="shrink-0">
|
||||||
{formatDate(attachment.purchaseDate)}
|
{formatDate(attachment.purchaseDate)}
|
||||||
</span>
|
</span>
|
||||||
|
<span aria-hidden>·</span>
|
||||||
|
<span className="truncate" title={attachment.payerName}>
|
||||||
|
{attachment.payerName}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* Transação e Valor */}
|
{/* Transação e Valor */}
|
||||||
<div className="flex items-start justify-between gap-2">
|
<div className="flex items-start justify-between gap-2">
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import {
|
|||||||
RiAttachmentLine,
|
RiAttachmentLine,
|
||||||
RiFilePdf2Line,
|
RiFilePdf2Line,
|
||||||
RiImageLine,
|
RiImageLine,
|
||||||
|
RiUserLine,
|
||||||
|
RiVerifiedBadgeFill,
|
||||||
} from "@remixicon/react";
|
} from "@remixicon/react";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import type React from "react";
|
import type React from "react";
|
||||||
@@ -17,9 +19,17 @@ import type { TransactionDialogOptions } from "@/features/transactions/actions/f
|
|||||||
import { fetchTransactionDialogOptionsAction } from "@/features/transactions/actions/fetch-dialog-options";
|
import { fetchTransactionDialogOptionsAction } from "@/features/transactions/actions/fetch-dialog-options";
|
||||||
import { TransactionDetailsDialog } from "@/features/transactions/components/dialogs/transaction-details-dialog";
|
import { TransactionDetailsDialog } from "@/features/transactions/components/dialogs/transaction-details-dialog";
|
||||||
import { TransactionDialog } from "@/features/transactions/components/dialogs/transaction-dialog/transaction-dialog";
|
import { TransactionDialog } from "@/features/transactions/components/dialogs/transaction-dialog/transaction-dialog";
|
||||||
|
import { PayerSelectContent } from "@/features/transactions/components/select-items";
|
||||||
import type { TransactionItem } from "@/features/transactions/components/types";
|
import type { TransactionItem } from "@/features/transactions/components/types";
|
||||||
import { EmptyState } from "@/shared/components/feedback/empty-state";
|
import { EmptyState } from "@/shared/components/feedback/empty-state";
|
||||||
import { Card, CardContent } from "@/shared/components/ui/card";
|
import { Card, CardContent } from "@/shared/components/ui/card";
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from "@/shared/components/ui/select";
|
||||||
import { cn } from "@/shared/utils/ui";
|
import { cn } from "@/shared/utils/ui";
|
||||||
|
|
||||||
type FilterType = "all" | "images" | "pdfs";
|
type FilterType = "all" | "images" | "pdfs";
|
||||||
@@ -73,11 +83,18 @@ const FILTERS: {
|
|||||||
|
|
||||||
interface AttachmentsPageProps {
|
interface AttachmentsPageProps {
|
||||||
attachments: AttachmentForPeriod[];
|
attachments: AttachmentForPeriod[];
|
||||||
|
adminPayerId: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function AttachmentsPage({ attachments }: AttachmentsPageProps) {
|
const ALL_PAYERS = "all";
|
||||||
|
|
||||||
|
export function AttachmentsPage({
|
||||||
|
attachments,
|
||||||
|
adminPayerId,
|
||||||
|
}: AttachmentsPageProps) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [filter, setFilter] = useState<FilterType>("all");
|
const [filter, setFilter] = useState<FilterType>("all");
|
||||||
|
const [payerFilter, setPayerFilter] = useState(adminPayerId);
|
||||||
const [selectedIndex, setSelectedIndex] = useState(-1);
|
const [selectedIndex, setSelectedIndex] = useState(-1);
|
||||||
const [transactionDetails, setTransactionDetails] =
|
const [transactionDetails, setTransactionDetails] =
|
||||||
useState<TransactionItem | null>(null);
|
useState<TransactionItem | null>(null);
|
||||||
@@ -93,21 +110,44 @@ export function AttachmentsPage({ attachments }: AttachmentsPageProps) {
|
|||||||
const [dialogOptions, setDialogOptions] =
|
const [dialogOptions, setDialogOptions] =
|
||||||
useState<TransactionDialogOptions | null>(null);
|
useState<TransactionDialogOptions | null>(null);
|
||||||
|
|
||||||
const filteredAttachments = attachments.filter((a) => {
|
const payerOptions = Array.from(
|
||||||
|
new Map(
|
||||||
|
attachments.map((attachment) => [
|
||||||
|
attachment.payerId,
|
||||||
|
{
|
||||||
|
value: attachment.payerId,
|
||||||
|
label: attachment.payerName,
|
||||||
|
avatarUrl: attachment.payerAvatarUrl,
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
).values(),
|
||||||
|
).sort((a, b) =>
|
||||||
|
a.label.localeCompare(b.label, "pt-BR", { sensitivity: "base" }),
|
||||||
|
);
|
||||||
|
|
||||||
|
const payerAttachments = attachments.filter(
|
||||||
|
(attachment) =>
|
||||||
|
payerFilter === ALL_PAYERS || attachment.payerId === payerFilter,
|
||||||
|
);
|
||||||
|
const selectedPayer = payerOptions.find(
|
||||||
|
(option) => option.value === payerFilter,
|
||||||
|
);
|
||||||
|
|
||||||
|
const filteredAttachments = payerAttachments.filter((a) => {
|
||||||
if (filter === "images") return a.mimeType.startsWith("image/");
|
if (filter === "images") return a.mimeType.startsWith("image/");
|
||||||
if (filter === "pdfs") return a.mimeType === "application/pdf";
|
if (filter === "pdfs") return a.mimeType === "application/pdf";
|
||||||
return true;
|
return true;
|
||||||
});
|
});
|
||||||
|
|
||||||
const imageCount = attachments.filter((a) =>
|
const imageCount = payerAttachments.filter((a) =>
|
||||||
a.mimeType.startsWith("image/"),
|
a.mimeType.startsWith("image/"),
|
||||||
).length;
|
).length;
|
||||||
const pdfCount = attachments.filter(
|
const pdfCount = payerAttachments.filter(
|
||||||
(a) => a.mimeType === "application/pdf",
|
(a) => a.mimeType === "application/pdf",
|
||||||
).length;
|
).length;
|
||||||
|
|
||||||
const counts: Record<FilterType, number> = {
|
const counts: Record<FilterType, number> = {
|
||||||
all: attachments.length,
|
all: payerAttachments.length,
|
||||||
images: imageCount,
|
images: imageCount,
|
||||||
pdfs: pdfCount,
|
pdfs: pdfCount,
|
||||||
};
|
};
|
||||||
@@ -161,6 +201,67 @@ export function AttachmentsPage({ attachments }: AttachmentsPageProps) {
|
|||||||
{filter !== "all" &&
|
{filter !== "all" &&
|
||||||
` · ${FILTERS.find((f) => f.value === filter)?.label.toLowerCase()}`}
|
` · ${FILTERS.find((f) => f.value === filter)?.label.toLowerCase()}`}
|
||||||
</p>
|
</p>
|
||||||
|
<div className="flex w-full flex-wrap items-center justify-end gap-2 sm:w-auto">
|
||||||
|
<Select
|
||||||
|
value={payerFilter}
|
||||||
|
onValueChange={(value) => {
|
||||||
|
setPayerFilter(value);
|
||||||
|
setSelectedIndex(-1);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<SelectTrigger
|
||||||
|
size="sm"
|
||||||
|
className="min-w-44 flex-1 sm:flex-none"
|
||||||
|
>
|
||||||
|
<SelectValue placeholder="Pessoa">
|
||||||
|
{payerFilter === ALL_PAYERS ? (
|
||||||
|
<span className="flex items-center gap-2">
|
||||||
|
<RiUserLine className="size-4" />
|
||||||
|
Todas as pessoas
|
||||||
|
</span>
|
||||||
|
) : selectedPayer ? (
|
||||||
|
<span className="flex items-center gap-1.5">
|
||||||
|
<PayerSelectContent
|
||||||
|
label={selectedPayer.label}
|
||||||
|
avatarUrl={selectedPayer.avatarUrl}
|
||||||
|
/>
|
||||||
|
{selectedPayer.value === adminPayerId && (
|
||||||
|
<RiVerifiedBadgeFill
|
||||||
|
className="size-4 text-blue-500"
|
||||||
|
aria-label="Pessoa principal"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
|
</SelectValue>
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent align="end">
|
||||||
|
<SelectItem value={ALL_PAYERS}>
|
||||||
|
<span className="flex items-center gap-2">
|
||||||
|
<span className="flex size-6 items-center justify-center rounded-full bg-muted">
|
||||||
|
<RiUserLine className="size-3.5" />
|
||||||
|
</span>
|
||||||
|
Todas as pessoas
|
||||||
|
</span>
|
||||||
|
</SelectItem>
|
||||||
|
{payerOptions.map((option) => (
|
||||||
|
<SelectItem key={option.value} value={option.value}>
|
||||||
|
<span className="flex items-center gap-1.5">
|
||||||
|
<PayerSelectContent
|
||||||
|
label={option.label}
|
||||||
|
avatarUrl={option.avatarUrl}
|
||||||
|
/>
|
||||||
|
{option.value === adminPayerId && (
|
||||||
|
<RiVerifiedBadgeFill
|
||||||
|
className="size-4 text-blue-500"
|
||||||
|
aria-label="Pessoa principal"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
<div className="flex items-center gap-1 rounded-lg border p-1">
|
<div className="flex items-center gap-1 rounded-lg border p-1">
|
||||||
{FILTERS.map(({ value, label, icon }) => (
|
{FILTERS.map(({ value, label, icon }) => (
|
||||||
<button
|
<button
|
||||||
@@ -193,13 +294,18 @@ export function AttachmentsPage({ attachments }: AttachmentsPageProps) {
|
|||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
{filteredAttachments.length === 0 ? (
|
{filteredAttachments.length === 0 ? (
|
||||||
<div className="flex w-full items-center justify-center py-12">
|
<div className="flex w-full items-center justify-center py-12">
|
||||||
<EmptyState
|
<EmptyState
|
||||||
media={<RiAttachmentLine className="size-6 text-primary" />}
|
media={<RiAttachmentLine className="size-6 text-primary" />}
|
||||||
title="Nenhum anexo encontrado"
|
title="Nenhum anexo encontrado"
|
||||||
description="Não há anexos do tipo selecionado neste mês."
|
description={
|
||||||
|
payerAttachments.length === 0
|
||||||
|
? "Não há anexos desta pessoa neste mês."
|
||||||
|
: "Não há anexos do tipo selecionado neste mês."
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { cacheLife, cacheTag } from "next/cache";
|
|||||||
import {
|
import {
|
||||||
attachments,
|
attachments,
|
||||||
categories,
|
categories,
|
||||||
|
payers,
|
||||||
transactionAttachments,
|
transactionAttachments,
|
||||||
transactions,
|
transactions,
|
||||||
} from "@/db/schema";
|
} from "@/db/schema";
|
||||||
@@ -21,11 +22,20 @@ export type AttachmentForPeriod = {
|
|||||||
purchaseDate: Date;
|
purchaseDate: Date;
|
||||||
categoryName: string | null;
|
categoryName: string | null;
|
||||||
categoryIcon: string | null;
|
categoryIcon: string | null;
|
||||||
|
payerId: string;
|
||||||
|
payerName: string;
|
||||||
|
payerAvatarUrl: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type AttachmentsPageData = {
|
||||||
|
attachments: AttachmentForPeriod[];
|
||||||
|
adminPayerId: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export async function fetchAttachmentsForPeriod(
|
export async function fetchAttachmentsForPeriod(
|
||||||
userId: string,
|
userId: string,
|
||||||
period: string,
|
period: string,
|
||||||
|
payerScope?: string | "all",
|
||||||
): Promise<AttachmentForPeriod[]> {
|
): Promise<AttachmentForPeriod[]> {
|
||||||
"use cache";
|
"use cache";
|
||||||
cacheTag(`dashboard-${userId}`);
|
cacheTag(`dashboard-${userId}`);
|
||||||
@@ -33,8 +43,9 @@ export async function fetchAttachmentsForPeriod(
|
|||||||
|
|
||||||
const adminPayerId = await getAdminPayerId(userId);
|
const adminPayerId = await getAdminPayerId(userId);
|
||||||
if (!adminPayerId) return [];
|
if (!adminPayerId) return [];
|
||||||
|
const payerId = payerScope ?? adminPayerId;
|
||||||
|
|
||||||
return db
|
const rows = await db
|
||||||
.select({
|
.select({
|
||||||
attachmentId: attachments.id,
|
attachmentId: attachments.id,
|
||||||
fileName: attachments.fileName,
|
fileName: attachments.fileName,
|
||||||
@@ -47,6 +58,9 @@ export async function fetchAttachmentsForPeriod(
|
|||||||
purchaseDate: transactions.purchaseDate,
|
purchaseDate: transactions.purchaseDate,
|
||||||
categoryName: categories.name,
|
categoryName: categories.name,
|
||||||
categoryIcon: categories.icon,
|
categoryIcon: categories.icon,
|
||||||
|
payerId: payers.id,
|
||||||
|
payerName: payers.name,
|
||||||
|
payerAvatarUrl: payers.avatarUrl,
|
||||||
})
|
})
|
||||||
.from(transactionAttachments)
|
.from(transactionAttachments)
|
||||||
.innerJoin(
|
.innerJoin(
|
||||||
@@ -61,10 +75,32 @@ export async function fetchAttachmentsForPeriod(
|
|||||||
and(
|
and(
|
||||||
eq(transactionAttachments.transactionId, transactions.id),
|
eq(transactionAttachments.transactionId, transactions.id),
|
||||||
eq(transactions.userId, userId),
|
eq(transactions.userId, userId),
|
||||||
eq(transactions.payerId, adminPayerId),
|
|
||||||
eq(transactions.period, period),
|
eq(transactions.period, period),
|
||||||
|
payerId === "all" ? undefined : eq(transactions.payerId, payerId),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.innerJoin(
|
||||||
|
payers,
|
||||||
|
and(eq(transactions.payerId, payers.id), eq(payers.userId, userId)),
|
||||||
|
)
|
||||||
|
.leftJoin(
|
||||||
|
categories,
|
||||||
|
and(
|
||||||
|
eq(transactions.categoryId, categories.id),
|
||||||
|
eq(categories.userId, userId),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
.leftJoin(categories, eq(transactions.categoryId, categories.id))
|
|
||||||
.orderBy(desc(transactions.purchaseDate), desc(attachments.id));
|
.orderBy(desc(transactions.purchaseDate), desc(attachments.id));
|
||||||
|
|
||||||
|
return rows;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchAttachmentsPageData(
|
||||||
|
userId: string,
|
||||||
|
period: string,
|
||||||
|
): Promise<AttachmentsPageData | null> {
|
||||||
|
const adminPayerId = await getAdminPayerId(userId);
|
||||||
|
if (!adminPayerId) return null;
|
||||||
|
const rows = await fetchAttachmentsForPeriod(userId, period, "all");
|
||||||
|
return { attachments: rows, adminPayerId };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import {
|
|||||||
} from "@remixicon/react";
|
} from "@remixicon/react";
|
||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
import MoneyValues from "@/shared/components/money-values";
|
import MoneyValues from "@/shared/components/money-values";
|
||||||
|
import { Badge } from "@/shared/components/ui/badge";
|
||||||
import {
|
import {
|
||||||
Card,
|
Card,
|
||||||
CardContent,
|
CardContent,
|
||||||
@@ -23,6 +24,10 @@ import {
|
|||||||
TooltipTrigger,
|
TooltipTrigger,
|
||||||
} from "@/shared/components/ui/tooltip";
|
} from "@/shared/components/ui/tooltip";
|
||||||
import { resolveCardBrandAsset } from "@/shared/lib/cards/brand-assets";
|
import { resolveCardBrandAsset } from "@/shared/lib/cards/brand-assets";
|
||||||
|
import {
|
||||||
|
INVOICE_PAYMENT_STATUS,
|
||||||
|
type InvoicePaymentStatus,
|
||||||
|
} from "@/shared/lib/invoices";
|
||||||
import { resolveLogoSrc } from "@/shared/lib/logo";
|
import { resolveLogoSrc } from "@/shared/lib/logo";
|
||||||
import { cn } from "@/shared/utils/ui";
|
import { cn } from "@/shared/utils/ui";
|
||||||
|
|
||||||
@@ -37,6 +42,7 @@ interface CardItemProps {
|
|||||||
limitAvailable?: number;
|
limitAvailable?: number;
|
||||||
currentInvoiceAmount: number;
|
currentInvoiceAmount: number;
|
||||||
currentInvoiceLabel: string;
|
currentInvoiceLabel: string;
|
||||||
|
currentInvoiceStatus: InvoicePaymentStatus | null;
|
||||||
accountName: string;
|
accountName: string;
|
||||||
logo?: string | null;
|
logo?: string | null;
|
||||||
note?: string | null;
|
note?: string | null;
|
||||||
@@ -58,6 +64,7 @@ export function CardItem({
|
|||||||
limitAvailable,
|
limitAvailable,
|
||||||
currentInvoiceAmount,
|
currentInvoiceAmount,
|
||||||
currentInvoiceLabel,
|
currentInvoiceLabel,
|
||||||
|
currentInvoiceStatus,
|
||||||
accountName: _accountName,
|
accountName: _accountName,
|
||||||
logo,
|
logo,
|
||||||
note,
|
note,
|
||||||
@@ -80,6 +87,8 @@ export function CardItem({
|
|||||||
const logoPath = resolveLogoSrc(logo);
|
const logoPath = resolveLogoSrc(logo);
|
||||||
const brandAsset = resolveCardBrandAsset(brand);
|
const brandAsset = resolveCardBrandAsset(brand);
|
||||||
const isInactive = status?.toLowerCase() === "inativo";
|
const isInactive = status?.toLowerCase() === "inativo";
|
||||||
|
const isCurrentInvoicePaid =
|
||||||
|
currentInvoiceStatus === INVOICE_PAYMENT_STATUS.PAID;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card className="flex flex-col p-6 w-full">
|
<Card className="flex flex-col p-6 w-full">
|
||||||
@@ -175,10 +184,17 @@ export function CardItem({
|
|||||||
<span className="text-xs text-muted-foreground">
|
<span className="text-xs text-muted-foreground">
|
||||||
{currentInvoiceLabel}
|
{currentInvoiceLabel}
|
||||||
</span>
|
</span>
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
<MoneyValues
|
<MoneyValues
|
||||||
amount={currentInvoiceAmount}
|
amount={currentInvoiceAmount}
|
||||||
className="text-xl font-semibold text-info"
|
className="text-xl font-semibold text-info"
|
||||||
/>
|
/>
|
||||||
|
{isCurrentInvoicePaid ? (
|
||||||
|
<Badge variant="success" className="text-xs">
|
||||||
|
Paga
|
||||||
|
</Badge>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex gap-2 justify-between w-full">
|
<div className="flex gap-2 justify-between w-full">
|
||||||
|
|||||||
@@ -144,6 +144,7 @@ export function CardsPage({
|
|||||||
limitAvailable={card.limitAvailable ?? card.limit ?? null}
|
limitAvailable={card.limitAvailable ?? card.limit ?? null}
|
||||||
currentInvoiceAmount={card.currentInvoiceAmount}
|
currentInvoiceAmount={card.currentInvoiceAmount}
|
||||||
currentInvoiceLabel={card.currentInvoiceLabel}
|
currentInvoiceLabel={card.currentInvoiceLabel}
|
||||||
|
currentInvoiceStatus={card.currentInvoiceStatus}
|
||||||
accountName={card.accountName}
|
accountName={card.accountName}
|
||||||
logo={card.logo}
|
logo={card.logo}
|
||||||
note={card.note}
|
note={card.note}
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import type { InvoicePaymentStatus } from "@/shared/lib/invoices";
|
||||||
|
|
||||||
export type Card = {
|
export type Card = {
|
||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
@@ -14,6 +16,7 @@ export type Card = {
|
|||||||
limitAvailable: number;
|
limitAvailable: number;
|
||||||
currentInvoiceAmount: number;
|
currentInvoiceAmount: number;
|
||||||
currentInvoiceLabel: string;
|
currentInvoiceLabel: string;
|
||||||
|
currentInvoiceStatus: InvoicePaymentStatus | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type CardFormValues = {
|
export type CardFormValues = {
|
||||||
|
|||||||
@@ -11,7 +11,11 @@ import {
|
|||||||
} from "drizzle-orm";
|
} from "drizzle-orm";
|
||||||
import { cards, financialAccounts, invoices, transactions } from "@/db/schema";
|
import { cards, financialAccounts, invoices, transactions } from "@/db/schema";
|
||||||
import { db } from "@/shared/lib/db";
|
import { db } from "@/shared/lib/db";
|
||||||
import { INVOICE_PAYMENT_STATUS } from "@/shared/lib/invoices";
|
import {
|
||||||
|
INVOICE_PAYMENT_STATUS,
|
||||||
|
INVOICE_STATUS_VALUES,
|
||||||
|
type InvoicePaymentStatus,
|
||||||
|
} from "@/shared/lib/invoices";
|
||||||
import { loadLogoOptions } from "@/shared/lib/logo/options";
|
import { loadLogoOptions } from "@/shared/lib/logo/options";
|
||||||
import {
|
import {
|
||||||
formatPeriodMonthShort,
|
formatPeriodMonthShort,
|
||||||
@@ -33,6 +37,7 @@ type CardData = {
|
|||||||
limitAvailable: number;
|
limitAvailable: number;
|
||||||
currentInvoiceAmount: number;
|
currentInvoiceAmount: number;
|
||||||
currentInvoiceLabel: string;
|
currentInvoiceLabel: string;
|
||||||
|
currentInvoiceStatus: InvoicePaymentStatus | null;
|
||||||
accountId: string;
|
accountId: string;
|
||||||
accountName: string;
|
accountName: string;
|
||||||
};
|
};
|
||||||
@@ -48,6 +53,12 @@ function formatCurrentInvoiceLabel(period: string) {
|
|||||||
return `Fatura ${formatPeriodMonthShort(period)}. ${year}`;
|
return `Fatura ${formatPeriodMonthShort(period)}. ${year}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function parseInvoiceStatus(value: unknown): InvoicePaymentStatus | null {
|
||||||
|
return INVOICE_STATUS_VALUES.includes(value as InvoicePaymentStatus)
|
||||||
|
? (value as InvoicePaymentStatus)
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
|
||||||
async function fetchCardsByStatus(
|
async function fetchCardsByStatus(
|
||||||
userId: string,
|
userId: string,
|
||||||
archived: boolean,
|
archived: boolean,
|
||||||
@@ -58,8 +69,14 @@ async function fetchCardsByStatus(
|
|||||||
}> {
|
}> {
|
||||||
const currentPeriod = getCurrentPeriod();
|
const currentPeriod = getCurrentPeriod();
|
||||||
const currentInvoiceLabel = formatCurrentInvoiceLabel(currentPeriod);
|
const currentInvoiceLabel = formatCurrentInvoiceLabel(currentPeriod);
|
||||||
const [cardRows, accountRows, logoOptions, usageRows, invoiceRows] =
|
const [
|
||||||
await Promise.all([
|
cardRows,
|
||||||
|
accountRows,
|
||||||
|
logoOptions,
|
||||||
|
usageRows,
|
||||||
|
invoiceRows,
|
||||||
|
invoiceStatusRows,
|
||||||
|
] = await Promise.all([
|
||||||
db.query.cards.findMany({
|
db.query.cards.findMany({
|
||||||
orderBy: (table, { desc }) => [desc(table.name)],
|
orderBy: (table, { desc }) => [desc(table.name)],
|
||||||
where: and(
|
where: and(
|
||||||
@@ -130,6 +147,15 @@ async function fetchCardsByStatus(
|
|||||||
),
|
),
|
||||||
)
|
)
|
||||||
.groupBy(transactions.cardId),
|
.groupBy(transactions.cardId),
|
||||||
|
db
|
||||||
|
.select({
|
||||||
|
cardId: invoices.cardId,
|
||||||
|
paymentStatus: invoices.paymentStatus,
|
||||||
|
})
|
||||||
|
.from(invoices)
|
||||||
|
.where(
|
||||||
|
and(eq(invoices.userId, userId), eq(invoices.period, currentPeriod)),
|
||||||
|
),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const usageMap = new Map<string, number>();
|
const usageMap = new Map<string, number>();
|
||||||
@@ -144,6 +170,13 @@ async function fetchCardsByStatus(
|
|||||||
invoiceMap.set(row.cardId, Math.abs(Number(row.total ?? 0)));
|
invoiceMap.set(row.cardId, Math.abs(Number(row.total ?? 0)));
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
const invoiceStatusMap = new Map<string, InvoicePaymentStatus>();
|
||||||
|
invoiceStatusRows.forEach((row) => {
|
||||||
|
if (!row.cardId) return;
|
||||||
|
const status = parseInvoiceStatus(row.paymentStatus);
|
||||||
|
if (!status) return;
|
||||||
|
invoiceStatusMap.set(row.cardId, status);
|
||||||
|
});
|
||||||
|
|
||||||
const cardList = cardRows.map((card) => ({
|
const cardList = cardRows.map((card) => ({
|
||||||
id: card.id,
|
id: card.id,
|
||||||
@@ -166,6 +199,7 @@ async function fetchCardsByStatus(
|
|||||||
})(),
|
})(),
|
||||||
currentInvoiceAmount: invoiceMap.get(card.id) ?? 0,
|
currentInvoiceAmount: invoiceMap.get(card.id) ?? 0,
|
||||||
currentInvoiceLabel,
|
currentInvoiceLabel,
|
||||||
|
currentInvoiceStatus: invoiceStatusMap.get(card.id) ?? null,
|
||||||
accountId: card.accountId,
|
accountId: card.accountId,
|
||||||
accountName:
|
accountName:
|
||||||
(card.financialAccount as { name?: string } | null)?.name ??
|
(card.financialAccount as { name?: string } | null)?.name ??
|
||||||
|
|||||||
@@ -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: {
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import {
|
|||||||
isIncomeBill,
|
isIncomeBill,
|
||||||
} from "@/features/dashboard/bills/bills-helpers";
|
} from "@/features/dashboard/bills/bills-helpers";
|
||||||
import type { DashboardBill } from "@/features/dashboard/bills/bills-queries";
|
import type { DashboardBill } from "@/features/dashboard/bills/bills-queries";
|
||||||
|
import { dashboardWidgetListStyles as styles } from "@/features/dashboard/components/dashboard-widget-list-styles";
|
||||||
import { EstablishmentLogo } from "@/shared/components/entity-avatar";
|
import { EstablishmentLogo } from "@/shared/components/entity-avatar";
|
||||||
import MoneyValues from "@/shared/components/money-values";
|
import MoneyValues from "@/shared/components/money-values";
|
||||||
import { Button } from "@/shared/components/ui/button";
|
import { Button } from "@/shared/components/ui/button";
|
||||||
@@ -47,25 +48,22 @@ export function BillListItem({ bill, period, onPay }: BillListItemProps) {
|
|||||||
const href = buildTransactionsHref(bill.name, period);
|
const href = buildTransactionsHref(bill.name, period);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<li className="flex items-center justify-between transition-all duration-300 py-1.5">
|
<li className={styles.row}>
|
||||||
<div className="flex min-w-0 flex-1 items-center gap-2 py-0.5">
|
<div className={styles.main}>
|
||||||
<EstablishmentLogo name={bill.name} size={37} />
|
<EstablishmentLogo name={bill.name} size={37} />
|
||||||
|
|
||||||
<div className="min-w-0">
|
<div className={styles.textStack}>
|
||||||
<Link
|
<Link href={href} className={styles.titleLink}>
|
||||||
href={href}
|
|
||||||
className="inline-flex max-w-full items-center gap-1 text-sm font-medium text-foreground underline-offset-2 hover:text-primary hover:underline"
|
|
||||||
>
|
|
||||||
<span className="truncate">{bill.name}</span>
|
<span className="truncate">{bill.name}</span>
|
||||||
</Link>
|
</Link>
|
||||||
<div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
|
<div className={styles.meta}>
|
||||||
{statusLabel ? (
|
{statusLabel ? (
|
||||||
statusTooltipLabel ? (
|
statusTooltipLabel ? (
|
||||||
<Tooltip>
|
<Tooltip>
|
||||||
<TooltipTrigger asChild>
|
<TooltipTrigger asChild>
|
||||||
<span
|
<span
|
||||||
className={cn(
|
className={cn(
|
||||||
"cursor-help rounded-full py-0.5",
|
"cursor-help",
|
||||||
bill.isSettled && "text-success font-semibold",
|
bill.isSettled && "text-success font-semibold",
|
||||||
overdue && "text-destructive font-semibold",
|
overdue && "text-destructive font-semibold",
|
||||||
)}
|
)}
|
||||||
@@ -80,7 +78,6 @@ export function BillListItem({ bill, period, onPay }: BillListItemProps) {
|
|||||||
) : (
|
) : (
|
||||||
<span
|
<span
|
||||||
className={cn(
|
className={cn(
|
||||||
"rounded-full py-0.5",
|
|
||||||
bill.isSettled && "text-success font-semibold",
|
bill.isSettled && "text-success font-semibold",
|
||||||
overdue && "text-destructive font-semibold",
|
overdue && "text-destructive font-semibold",
|
||||||
)}
|
)}
|
||||||
@@ -93,10 +90,10 @@ export function BillListItem({ bill, period, onPay }: BillListItemProps) {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex shrink-0 flex-col items-end">
|
<div className={styles.trailing}>
|
||||||
<MoneyValues className="font-medium" amount={bill.amount} />
|
<MoneyValues className={styles.trailingValue} amount={bill.amount} />
|
||||||
{bill.isSettled ? (
|
{bill.isSettled ? (
|
||||||
<span className="flex h-7 items-center gap-0.5 text-xs font-medium text-success">
|
<span className={`${styles.trailingMeta} text-success`}>
|
||||||
<RiCheckboxCircleFill className="size-3.5" />{" "}
|
<RiCheckboxCircleFill className="size-3.5" />{" "}
|
||||||
{income ? "Recebido" : "Pago"}
|
{income ? "Recebido" : "Pago"}
|
||||||
</span>
|
</span>
|
||||||
@@ -105,7 +102,7 @@ export function BillListItem({ bill, period, onPay }: BillListItemProps) {
|
|||||||
type="button"
|
type="button"
|
||||||
size="sm"
|
size="sm"
|
||||||
variant="link"
|
variant="link"
|
||||||
className="-mr-1.5 h-7 px-1.5 py-0"
|
className={styles.actionButton}
|
||||||
onClick={() => onPay(bill.id)}
|
onClick={() => onPay(bill.id)}
|
||||||
>
|
>
|
||||||
{overdue ? (
|
{overdue ? (
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import type { DashboardCategoryBreakdownItem } from "@/features/dashboard/categories/category-breakdown-helpers";
|
import type { DashboardCategoryBreakdownItem } from "@/features/dashboard/categories/category-breakdown-helpers";
|
||||||
|
import { dashboardWidgetListStyles as styles } from "@/features/dashboard/components/dashboard-widget-list-styles";
|
||||||
import { PercentageChangeIndicator } from "@/features/dashboard/components/percentage-change-indicator";
|
import { PercentageChangeIndicator } from "@/features/dashboard/components/percentage-change-indicator";
|
||||||
import { CategoryIconBadge } from "@/shared/components/entity-avatar";
|
import { CategoryIconBadge } from "@/shared/components/entity-avatar";
|
||||||
import MoneyValues from "@/shared/components/money-values";
|
import MoneyValues from "@/shared/components/money-values";
|
||||||
@@ -45,25 +46,23 @@ export function CategoryBreakdownListItem({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<div className="flex items-center justify-between gap-2 transition-all duration-300 py-1.5">
|
<div className={styles.row}>
|
||||||
<span className="w-3 shrink-0 text-left text-xs font-medium text-muted-foreground">
|
<span className={styles.rank}>{position}</span>
|
||||||
{position}
|
<div className={styles.main}>
|
||||||
</span>
|
|
||||||
<div className="flex min-w-0 flex-1 items-center gap-2">
|
|
||||||
<CategoryIconBadge
|
<CategoryIconBadge
|
||||||
icon={category.categoryIcon}
|
icon={category.categoryIcon}
|
||||||
name={category.categoryName}
|
name={category.categoryName}
|
||||||
/>
|
/>
|
||||||
<div className="min-w-0 flex-1">
|
<div className={styles.textStack}>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<Link
|
<Link
|
||||||
href={`/categories/${category.categoryId}?periodo=${periodParam}`}
|
href={`/categories/${category.categoryId}?periodo=${periodParam}`}
|
||||||
className="flex max-w-full items-center gap-1 text-sm font-medium text-foreground underline-offset-2 hover:text-primary hover:underline"
|
className={styles.titleLink}
|
||||||
>
|
>
|
||||||
<span className="truncate">{category.categoryName}</span>
|
<span className="truncate">{category.categoryName}</span>
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-wrap items-center gap-x-1 text-xs text-muted-foreground">
|
<div className={styles.meta}>
|
||||||
<span>
|
<span>
|
||||||
{formatPercentage(
|
{formatPercentage(
|
||||||
category.percentageOfTotal,
|
category.percentageOfTotal,
|
||||||
@@ -97,23 +96,24 @@ export function CategoryBreakdownListItem({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex shrink-0 flex-col items-end gap-0.5">
|
<div className={styles.trailing}>
|
||||||
<MoneyValues
|
<MoneyValues
|
||||||
className="text-foreground font-medium"
|
className={styles.trailingValue}
|
||||||
amount={category.currentAmount}
|
amount={category.currentAmount}
|
||||||
/>
|
/>
|
||||||
|
{category.percentageChange !== null ? (
|
||||||
|
<span className={`${styles.trailingMeta} text-muted-foreground`}>
|
||||||
<PercentageChangeIndicator
|
<PercentageChangeIndicator
|
||||||
value={category.percentageChange}
|
value={category.percentageChange}
|
||||||
label={
|
label={formatPercentage(
|
||||||
category.percentageChange !== null
|
|
||||||
? formatPercentage(
|
|
||||||
category.percentageChange,
|
category.percentageChange,
|
||||||
config.percentageDigits,
|
config.percentageDigits,
|
||||||
)
|
)}
|
||||||
: undefined
|
|
||||||
}
|
|
||||||
positiveTrend={config.positiveTrend}
|
positiveTrend={config.positiveTrend}
|
||||||
/>
|
/>
|
||||||
|
<span>vs. mês ant.</span>
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
export const dashboardWidgetListStyles = {
|
||||||
|
row: "flex min-h-[3.25rem] items-center justify-between gap-2 py-1.5 transition-all duration-300",
|
||||||
|
main: "flex min-w-0 flex-1 items-center gap-2",
|
||||||
|
textStack: "min-w-0 flex-1 space-y-0.5",
|
||||||
|
title: "truncate text-sm font-medium leading-5 text-foreground",
|
||||||
|
titleLink:
|
||||||
|
"inline-flex max-w-full items-center gap-1 text-sm font-medium leading-5 text-foreground underline-offset-2 hover:text-primary hover:underline",
|
||||||
|
meta: "flex min-h-4 flex-wrap items-center gap-x-2 gap-y-0.5 text-xs leading-4 text-muted-foreground",
|
||||||
|
rank: "w-3 shrink-0 text-left text-xs font-medium leading-4 text-muted-foreground",
|
||||||
|
trailing:
|
||||||
|
"flex min-w-[5.75rem] shrink-0 flex-col items-end gap-0.5 text-right",
|
||||||
|
trailingValue: "font-medium leading-5",
|
||||||
|
trailingMeta: "flex h-5 items-center gap-0.5 text-xs font-medium leading-4",
|
||||||
|
actionButton: "-mr-1 h-5 px-1 py-0 text-xs leading-4",
|
||||||
|
};
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { RiPencilLine } from "@remixicon/react";
|
import { RiPencilLine } from "@remixicon/react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
|
import { dashboardWidgetListStyles as styles } from "@/features/dashboard/components/dashboard-widget-list-styles";
|
||||||
import {
|
import {
|
||||||
clampGoalProgress,
|
clampGoalProgress,
|
||||||
formatGoalProgressPercentage,
|
formatGoalProgressPercentage,
|
||||||
@@ -30,7 +31,7 @@ export function GoalProgressItem({ item, onEdit }: GoalProgressItemProps) {
|
|||||||
const usedPercentageLabel = formatGoalProgressPercentage(item.usedPercentage);
|
const usedPercentageLabel = formatGoalProgressPercentage(item.usedPercentage);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<li className="group py-2 transition-all duration-300">
|
<li className="group py-1.5 transition-all duration-300">
|
||||||
<div className="flex items-start justify-between gap-3">
|
<div className="flex items-start justify-between gap-3">
|
||||||
<div className="flex min-w-0 flex-1 items-start gap-2">
|
<div className="flex min-w-0 flex-1 items-start gap-2">
|
||||||
<CategoryIconBadge
|
<CategoryIconBadge
|
||||||
@@ -42,16 +43,14 @@ export function GoalProgressItem({ item, onEdit }: GoalProgressItemProps) {
|
|||||||
{item.categoryId ? (
|
{item.categoryId ? (
|
||||||
<Link
|
<Link
|
||||||
href={`/categories/${item.categoryId}?periodo=${formatPeriodForUrl(item.period)}`}
|
href={`/categories/${item.categoryId}?periodo=${formatPeriodForUrl(item.period)}`}
|
||||||
className="block truncate text-sm font-medium text-foreground underline-offset-2 hover:text-primary hover:underline"
|
className={`${styles.title} block underline-offset-2 hover:text-primary hover:underline`}
|
||||||
>
|
>
|
||||||
{item.categoryName}
|
{item.categoryName}
|
||||||
</Link>
|
</Link>
|
||||||
) : (
|
) : (
|
||||||
<p className="truncate text-sm font-medium text-foreground">
|
<p className={styles.title}>{item.categoryName}</p>
|
||||||
{item.categoryName}
|
|
||||||
</p>
|
|
||||||
)}
|
)}
|
||||||
<p className="mt-0.5 text-xs text-muted-foreground">
|
<p className="mt-0.5 text-xs leading-4 text-muted-foreground">
|
||||||
<MoneyValues className="font-medium" amount={item.spentAmount} />{" "}
|
<MoneyValues className="font-medium" amount={item.spentAmount} />{" "}
|
||||||
de{" "}
|
de{" "}
|
||||||
<MoneyValues className="font-medium" amount={item.budgetAmount} />
|
<MoneyValues className="font-medium" amount={item.budgetAmount} />
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
import {
|
import {
|
||||||
RiBankCard2Line,
|
RiBankCard2Line,
|
||||||
|
RiChat1Line,
|
||||||
RiCheckboxCircleFill,
|
RiCheckboxCircleFill,
|
||||||
RiFileList2Line,
|
RiFileList2Line,
|
||||||
RiTimeLine,
|
RiTimeLine,
|
||||||
@@ -30,6 +31,11 @@ import {
|
|||||||
DialogTitle,
|
DialogTitle,
|
||||||
} from "@/shared/components/ui/dialog";
|
} from "@/shared/components/ui/dialog";
|
||||||
import { Progress } from "@/shared/components/ui/progress";
|
import { Progress } from "@/shared/components/ui/progress";
|
||||||
|
import {
|
||||||
|
Tooltip,
|
||||||
|
TooltipContent,
|
||||||
|
TooltipTrigger,
|
||||||
|
} from "@/shared/components/ui/tooltip";
|
||||||
import { resolveLogoSrc } from "@/shared/lib/logo";
|
import { resolveLogoSrc } from "@/shared/lib/logo";
|
||||||
import { cn } from "@/shared/utils";
|
import { cn } from "@/shared/utils";
|
||||||
import type { InstallmentGroup } from "./types";
|
import type { InstallmentGroup } from "./types";
|
||||||
@@ -83,6 +89,7 @@ export function InstallmentGroupCard({
|
|||||||
);
|
);
|
||||||
const cardLogoSrc = resolveLogoSrc(group.cartaoLogo);
|
const cardLogoSrc = resolveLogoSrc(group.cartaoLogo);
|
||||||
const cardName = group.cartaoName ?? "Compra parcelada";
|
const cardName = group.cartaoName ?? "Compra parcelada";
|
||||||
|
const hasNote = Boolean(group.note?.trim().length);
|
||||||
const untrackedLabel =
|
const untrackedLabel =
|
||||||
group.untrackedInstallments === 1
|
group.untrackedInstallments === 1
|
||||||
? "1 parcela anterior fora do acompanhamento"
|
? "1 parcela anterior fora do acompanhamento"
|
||||||
@@ -121,8 +128,28 @@ export function InstallmentGroupCard({
|
|||||||
<div className="flex items-center gap-3 flex-wrap">
|
<div className="flex items-center gap-3 flex-wrap">
|
||||||
<EstablishmentLogo name={group.name} size={40} />
|
<EstablishmentLogo name={group.name} size={40} />
|
||||||
<div className="flex-1 min-w-0">
|
<div className="flex-1 min-w-0">
|
||||||
<CardTitle className="text-base truncate">
|
<CardTitle className="flex items-center gap-1 text-base">
|
||||||
{group.name}
|
<span className="truncate">{group.name}</span>
|
||||||
|
{hasNote ? (
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger asChild>
|
||||||
|
<span className="inline-flex shrink-0 rounded-full p-1 hover:bg-accent transition-colors duration-300">
|
||||||
|
<RiChat1Line
|
||||||
|
className="h-4 w-4 text-muted-foreground"
|
||||||
|
aria-hidden
|
||||||
|
/>
|
||||||
|
<span className="sr-only">Ver anotação</span>
|
||||||
|
</span>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent
|
||||||
|
side="top"
|
||||||
|
align="start"
|
||||||
|
className="max-w-xs whitespace-pre-line"
|
||||||
|
>
|
||||||
|
{group.note}
|
||||||
|
</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
) : null}
|
||||||
</CardTitle>
|
</CardTitle>
|
||||||
<CardDescription className="flex min-w-0 items-center gap-1 text-xs">
|
<CardDescription className="flex min-w-0 items-center gap-1 text-xs">
|
||||||
{cardLogoSrc ? (
|
{cardLogoSrc ? (
|
||||||
@@ -235,8 +262,28 @@ export function InstallmentGroupCard({
|
|||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<EstablishmentLogo name={group.name} size={32} />
|
<EstablishmentLogo name={group.name} size={32} />
|
||||||
<div className="min-w-0">
|
<div className="min-w-0">
|
||||||
<DialogTitle className="truncate text-base">
|
<DialogTitle className="flex items-center gap-1 text-base">
|
||||||
{group.name}
|
<span className="truncate">{group.name}</span>
|
||||||
|
{hasNote ? (
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger asChild>
|
||||||
|
<span className="inline-flex shrink-0 rounded-full p-1 hover:bg-accent transition-colors duration-300">
|
||||||
|
<RiChat1Line
|
||||||
|
className="h-4 w-4 text-muted-foreground"
|
||||||
|
aria-hidden
|
||||||
|
/>
|
||||||
|
<span className="sr-only">Ver anotação</span>
|
||||||
|
</span>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent
|
||||||
|
side="top"
|
||||||
|
align="start"
|
||||||
|
className="max-w-xs whitespace-pre-line"
|
||||||
|
>
|
||||||
|
{group.note}
|
||||||
|
</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
) : null}
|
||||||
</DialogTitle>
|
</DialogTitle>
|
||||||
<div className="mt-0.5 flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground">
|
<div className="mt-0.5 flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground">
|
||||||
{cardLogoSrc ? (
|
{cardLogoSrc ? (
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { RiCheckboxCircleFill, RiGroupLine } from "@remixicon/react";
|
import { RiCheckboxCircleFill, RiGroupLine } from "@remixicon/react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
|
import { dashboardWidgetListStyles as styles } from "@/features/dashboard/components/dashboard-widget-list-styles";
|
||||||
import { PercentageChangeIndicator } from "@/features/dashboard/components/percentage-change-indicator";
|
import { PercentageChangeIndicator } from "@/features/dashboard/components/percentage-change-indicator";
|
||||||
import {
|
import {
|
||||||
buildInvoiceDetailsHref,
|
buildInvoiceDetailsHref,
|
||||||
@@ -62,18 +63,14 @@ export function InvoiceListItem({ invoice, onPay }: InvoiceListItemProps) {
|
|||||||
: null;
|
: null;
|
||||||
|
|
||||||
const linkNode = (
|
const linkNode = (
|
||||||
<Link
|
<Link prefetch href={detailHref} className={styles.titleLink}>
|
||||||
prefetch
|
|
||||||
href={detailHref}
|
|
||||||
className="inline-flex max-w-full items-center gap-1 text-sm font-medium text-foreground underline-offset-2 hover:text-primary hover:underline"
|
|
||||||
>
|
|
||||||
<span className="truncate">{invoice.cardName}</span>
|
<span className="truncate">{invoice.cardName}</span>
|
||||||
</Link>
|
</Link>
|
||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<li className="flex items-center justify-between transition-all duration-300 py-1.5">
|
<li className={styles.row}>
|
||||||
<div className="flex min-w-0 flex-1 items-center gap-2 py-1">
|
<div className={styles.main}>
|
||||||
<InvoiceLogo
|
<InvoiceLogo
|
||||||
cardName={invoice.cardName}
|
cardName={invoice.cardName}
|
||||||
logo={invoice.logo}
|
logo={invoice.logo}
|
||||||
@@ -81,7 +78,7 @@ export function InvoiceListItem({ invoice, onPay }: InvoiceListItemProps) {
|
|||||||
containerClassName="size-9.5"
|
containerClassName="size-9.5"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<div className="min-w-0">
|
<div className={styles.textStack}>
|
||||||
<div className="flex max-w-full items-center gap-1">
|
<div className="flex max-w-full items-center gap-1">
|
||||||
{hasBreakdown ? (
|
{hasBreakdown ? (
|
||||||
<HoverCard openDelay={150}>
|
<HoverCard openDelay={150}>
|
||||||
@@ -123,9 +120,14 @@ export function InvoiceListItem({ invoice, onPay }: InvoiceListItemProps) {
|
|||||||
className="font-medium"
|
className="font-medium"
|
||||||
amount={share.amount}
|
amount={share.amount}
|
||||||
/>
|
/>
|
||||||
|
{share.percentageChange !== null ? (
|
||||||
|
<span className="flex items-center gap-1 text-xs text-muted-foreground">
|
||||||
<PercentageChangeIndicator
|
<PercentageChangeIndicator
|
||||||
value={share.percentageChange}
|
value={share.percentageChange}
|
||||||
/>
|
/>
|
||||||
|
<span>vs. mês ant.</span>
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
@@ -150,7 +152,7 @@ export function InvoiceListItem({ invoice, onPay }: InvoiceListItemProps) {
|
|||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
|
<div className={styles.meta}>
|
||||||
{!isPaid ? (
|
{!isPaid ? (
|
||||||
dueTooltipLabel ? (
|
dueTooltipLabel ? (
|
||||||
<Tooltip>
|
<Tooltip>
|
||||||
@@ -199,13 +201,13 @@ export function InvoiceListItem({ invoice, onPay }: InvoiceListItemProps) {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex shrink-0 flex-col items-end">
|
<div className={styles.trailing}>
|
||||||
<MoneyValues
|
<MoneyValues
|
||||||
className="font-medium"
|
className={styles.trailingValue}
|
||||||
amount={Math.abs(invoice.totalAmount)}
|
amount={Math.abs(invoice.totalAmount)}
|
||||||
/>
|
/>
|
||||||
{isPaid ? (
|
{isPaid ? (
|
||||||
<span className="flex h-7 items-center gap-0.5 text-xs font-medium text-success">
|
<span className={`${styles.trailingMeta} text-success`}>
|
||||||
<RiCheckboxCircleFill className="size-3.5" /> Pago
|
<RiCheckboxCircleFill className="size-3.5" /> Pago
|
||||||
</span>
|
</span>
|
||||||
) : (
|
) : (
|
||||||
@@ -213,7 +215,7 @@ export function InvoiceListItem({ invoice, onPay }: InvoiceListItemProps) {
|
|||||||
type="button"
|
type="button"
|
||||||
size="sm"
|
size="sm"
|
||||||
variant="link"
|
variant="link"
|
||||||
className="-mr-1.5 h-7 px-1.5 py-0"
|
className={styles.actionButton}
|
||||||
onClick={() => onPay(invoice.id)}
|
onClick={() => onPay(invoice.id)}
|
||||||
>
|
>
|
||||||
{isOverdue ? (
|
{isOverdue ? (
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import {
|
|||||||
RiFileList2Line,
|
RiFileList2Line,
|
||||||
RiPencilLine,
|
RiPencilLine,
|
||||||
} from "@remixicon/react";
|
} from "@remixicon/react";
|
||||||
|
import { dashboardWidgetListStyles as styles } from "@/features/dashboard/components/dashboard-widget-list-styles";
|
||||||
import type { Note } from "@/features/notes/components/types";
|
import type { Note } from "@/features/notes/components/types";
|
||||||
import {
|
import {
|
||||||
buildNoteDisplayTitle,
|
buildNoteDisplayTitle,
|
||||||
@@ -33,18 +34,16 @@ export function NoteListItem({
|
|||||||
const isTask = note.type === "tarefa";
|
const isTask = note.type === "tarefa";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<li className="group flex items-center justify-between gap-2 py-1.5 transition-all duration-300">
|
<li className={`group ${styles.row}`}>
|
||||||
<div className="min-w-0 flex-1">
|
<div className={styles.textStack}>
|
||||||
<p className="truncate text-sm font-medium text-foreground">
|
<p className={styles.title}>{displayTitle}</p>
|
||||||
{displayTitle}
|
<div className={styles.meta}>
|
||||||
</p>
|
|
||||||
<div className="mt-1 flex min-w-0 items-center gap-2">
|
|
||||||
{isTask ? (
|
{isTask ? (
|
||||||
<Badge variant="outline" className="h-5 px-1.5 text-xs">
|
<Badge variant="outline" className="h-5 px-1.5 text-xs">
|
||||||
{getNoteTasksSummary(note)}
|
{getNoteTasksSummary(note)}
|
||||||
</Badge>
|
</Badge>
|
||||||
) : null}
|
) : null}
|
||||||
<p className="truncate text-xs text-muted-foreground">
|
<p className="truncate">
|
||||||
<span className="inline-flex items-center gap-1">
|
<span className="inline-flex items-center gap-1">
|
||||||
<RiCalendarLine className="size-3.5 shrink-0" />
|
<RiCalendarLine className="size-3.5 shrink-0" />
|
||||||
{createdAtLabel}
|
{createdAtLabel}
|
||||||
@@ -53,7 +52,7 @@ export function NoteListItem({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex shrink-0 items-center gap-0.5">
|
<div className="flex min-w-[4.5rem] shrink-0 items-center justify-end gap-0.5">
|
||||||
<Tooltip>
|
<Tooltip>
|
||||||
<TooltipTrigger asChild>
|
<TooltipTrigger asChild>
|
||||||
<Button
|
<Button
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import type { ReactNode } from "react";
|
import type { ReactNode } from "react";
|
||||||
|
import { dashboardWidgetListStyles as styles } from "@/features/dashboard/components/dashboard-widget-list-styles";
|
||||||
import {
|
import {
|
||||||
formatPaymentBreakdownPercentage,
|
formatPaymentBreakdownPercentage,
|
||||||
formatPaymentBreakdownTransactionsLabel,
|
formatPaymentBreakdownTransactionsLabel,
|
||||||
@@ -31,10 +32,8 @@ export function PaymentBreakdownListItem({
|
|||||||
position,
|
position,
|
||||||
}: PaymentBreakdownListItemProps) {
|
}: PaymentBreakdownListItemProps) {
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center gap-2 transition-all duration-300 py-1">
|
<div className={styles.row}>
|
||||||
<span className="w-3 shrink-0 text-left text-xs font-medium text-muted-foreground">
|
<span className={styles.rank}>{position}</span>
|
||||||
{position}
|
|
||||||
</span>
|
|
||||||
<div
|
<div
|
||||||
className="flex size-9.5 shrink-0 items-center justify-center rounded-full"
|
className="flex size-9.5 shrink-0 items-center justify-center rounded-full"
|
||||||
style={{
|
style={{
|
||||||
@@ -45,26 +44,26 @@ export function PaymentBreakdownListItem({
|
|||||||
{item.icon}
|
{item.icon}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="min-w-0 flex-1">
|
<div className={styles.textStack}>
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between gap-2">
|
||||||
{item.href ? (
|
{item.href ? (
|
||||||
<Link
|
<Link href={item.href} className={styles.titleLink}>
|
||||||
href={item.href}
|
|
||||||
className="inline-flex items-center gap-1 text-sm font-medium text-foreground underline-offset-2 hover:text-primary hover:underline"
|
|
||||||
>
|
|
||||||
<span className="truncate">{item.title}</span>
|
<span className="truncate">{item.title}</span>
|
||||||
</Link>
|
</Link>
|
||||||
) : (
|
) : (
|
||||||
<p className="text-sm font-medium text-foreground">{item.title}</p>
|
<p className={styles.title}>{item.title}</p>
|
||||||
)}
|
)}
|
||||||
<MoneyValues className="shrink-0 font-medium" amount={item.amount} />
|
<MoneyValues
|
||||||
|
className={`shrink-0 ${styles.trailingValue}`}
|
||||||
|
amount={item.amount}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center justify-between text-xs text-muted-foreground">
|
<div className={styles.meta}>
|
||||||
<span>
|
<span>
|
||||||
{formatPaymentBreakdownTransactionsLabel(item.transactions)}
|
{formatPaymentBreakdownTransactionsLabel(item.transactions)}
|
||||||
</span>
|
</span>
|
||||||
<span>
|
<span className="ml-auto">
|
||||||
{formatPaymentBreakdownPercentage(item.percentage)} do total
|
{formatPaymentBreakdownPercentage(item.percentage)} do total
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import {
|
|||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { AttachmentPreview } from "@/features/attachments/components/attachment-preview";
|
import { AttachmentPreview } from "@/features/attachments/components/attachment-preview";
|
||||||
import type { AttachmentForPeriod } from "@/features/attachments/queries";
|
import type { AttachmentForPeriod } from "@/features/attachments/queries";
|
||||||
|
import { dashboardWidgetListStyles as styles } from "@/features/dashboard/components/dashboard-widget-list-styles";
|
||||||
import {
|
import {
|
||||||
Tooltip,
|
Tooltip,
|
||||||
TooltipContent,
|
TooltipContent,
|
||||||
@@ -77,7 +78,7 @@ export function AttachmentsWidget({ snapshot }: AttachmentsWidgetProps) {
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => setSelectedIndex(index)}
|
onClick={() => setSelectedIndex(index)}
|
||||||
className="flex w-full items-center gap-2 py-2 text-left"
|
className={`${styles.row} w-full text-left`}
|
||||||
>
|
>
|
||||||
<div className="shrink-0">
|
<div className="shrink-0">
|
||||||
{isPdf && <RiFilePdf2Line className="size-6 text-red-500" />}
|
{isPdf && <RiFilePdf2Line className="size-6 text-red-500" />}
|
||||||
@@ -86,10 +87,10 @@ export function AttachmentsWidget({ snapshot }: AttachmentsWidgetProps) {
|
|||||||
<RiFileLine className="size-6 text-muted-foreground" />
|
<RiFileLine className="size-6 text-muted-foreground" />
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="min-w-0 flex-1">
|
<div className={styles.textStack}>
|
||||||
<Tooltip>
|
<Tooltip>
|
||||||
<TooltipTrigger asChild>
|
<TooltipTrigger asChild>
|
||||||
<span className="block truncate text-sm font-medium text-foreground hover:underline">
|
<span className={`${styles.title} block hover:underline`}>
|
||||||
{attachment.fileName}
|
{attachment.fileName}
|
||||||
</span>
|
</span>
|
||||||
</TooltipTrigger>
|
</TooltipTrigger>
|
||||||
@@ -97,18 +98,18 @@ export function AttachmentsWidget({ snapshot }: AttachmentsWidgetProps) {
|
|||||||
{attachment.fileName}
|
{attachment.fileName}
|
||||||
</TooltipContent>
|
</TooltipContent>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
<span className="block truncate text-xs text-muted-foreground">
|
<span className={`${styles.meta} block truncate`}>
|
||||||
{attachment.transactionName}
|
{attachment.transactionName}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="shrink-0 text-right">
|
<div className={styles.trailing}>
|
||||||
<span className="block text-xs text-muted-foreground">
|
<span className="block text-xs leading-4 text-muted-foreground">
|
||||||
{formatDateOnly(attachment.purchaseDate, {
|
{formatDateOnly(attachment.purchaseDate, {
|
||||||
day: "2-digit",
|
day: "2-digit",
|
||||||
month: "2-digit",
|
month: "2-digit",
|
||||||
}) ?? "—"}
|
}) ?? "—"}
|
||||||
</span>
|
</span>
|
||||||
<span className="block text-xs text-muted-foreground/60">
|
<span className="block text-xs leading-4 text-muted-foreground/60">
|
||||||
{formatBytes(attachment.fileSize)}
|
{formatBytes(attachment.fileSize)}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -6,20 +6,26 @@ import {
|
|||||||
RiHistoryLine,
|
RiHistoryLine,
|
||||||
RiLineChartLine,
|
RiLineChartLine,
|
||||||
} from "@remixicon/react";
|
} from "@remixicon/react";
|
||||||
|
import Link from "next/link";
|
||||||
import type { DashboardCategoryBreakdownItem } from "@/features/dashboard/categories/category-breakdown-helpers";
|
import type { DashboardCategoryBreakdownItem } from "@/features/dashboard/categories/category-breakdown-helpers";
|
||||||
|
import { dashboardWidgetListStyles as styles } from "@/features/dashboard/components/dashboard-widget-list-styles";
|
||||||
import { PercentageChangeIndicator } from "@/features/dashboard/components/percentage-change-indicator";
|
import { PercentageChangeIndicator } from "@/features/dashboard/components/percentage-change-indicator";
|
||||||
import { CategoryIconBadge } from "@/shared/components/entity-avatar";
|
import { CategoryIconBadge } from "@/shared/components/entity-avatar";
|
||||||
import MoneyValues from "@/shared/components/money-values";
|
import MoneyValues from "@/shared/components/money-values";
|
||||||
import { WidgetEmptyState } from "@/shared/components/widgets/widget-empty-state";
|
import { WidgetEmptyState } from "@/shared/components/widgets/widget-empty-state";
|
||||||
import { formatPercentage } from "@/shared/utils/percentage";
|
import { formatPercentage } from "@/shared/utils/percentage";
|
||||||
|
import { formatPeriodForUrl } from "@/shared/utils/period";
|
||||||
|
|
||||||
type CategoryTrendsWidgetProps = {
|
type CategoryTrendsWidgetProps = {
|
||||||
categories: DashboardCategoryBreakdownItem[];
|
categories: DashboardCategoryBreakdownItem[];
|
||||||
|
period: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function CategoryTrendsWidget({
|
export function CategoryTrendsWidget({
|
||||||
categories,
|
categories,
|
||||||
|
period,
|
||||||
}: CategoryTrendsWidgetProps) {
|
}: CategoryTrendsWidgetProps) {
|
||||||
|
const periodParam = formatPeriodForUrl(period);
|
||||||
const trending = categories
|
const trending = categories
|
||||||
.filter((c) => c.percentageChange !== null && c.previousAmount > 0)
|
.filter((c) => c.percentageChange !== null && c.previousAmount > 0)
|
||||||
.sort(
|
.sort(
|
||||||
@@ -45,17 +51,20 @@ export function CategoryTrendsWidget({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<li key={category.categoryId}>
|
<li key={category.categoryId}>
|
||||||
<div className="-mx-2 flex items-center gap-3 rounded-md p-2">
|
<div className={styles.row}>
|
||||||
<CategoryIconBadge
|
<CategoryIconBadge
|
||||||
icon={category.categoryIcon}
|
icon={category.categoryIcon}
|
||||||
name={category.categoryName}
|
name={category.categoryName}
|
||||||
size="md"
|
size="md"
|
||||||
/>
|
/>
|
||||||
<div className="min-w-0 flex-1">
|
<div className={styles.textStack}>
|
||||||
<p className="truncate text-sm font-medium text-foreground">
|
<Link
|
||||||
{category.categoryName}
|
href={`/categories/${category.categoryId}?periodo=${periodParam}`}
|
||||||
</p>
|
className={styles.titleLink}
|
||||||
<p className="flex items-center gap-1.5 text-xs text-muted-foreground">
|
>
|
||||||
|
<span className="truncate">{category.categoryName}</span>
|
||||||
|
</Link>
|
||||||
|
<p className={styles.meta}>
|
||||||
<span
|
<span
|
||||||
className="inline-flex items-center gap-1"
|
className="inline-flex items-center gap-1"
|
||||||
title="Mês anterior"
|
title="Mês anterior"
|
||||||
@@ -81,6 +90,9 @@ export function CategoryTrendsWidget({
|
|||||||
</span>
|
</span>
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
<span
|
||||||
|
className={`${styles.trailingMeta} min-w-[5.75rem] justify-end text-muted-foreground`}
|
||||||
|
>
|
||||||
<PercentageChangeIndicator
|
<PercentageChangeIndicator
|
||||||
value={change}
|
value={change}
|
||||||
label={formatPercentage(change, {
|
label={formatPercentage(change, {
|
||||||
@@ -89,9 +101,11 @@ export function CategoryTrendsWidget({
|
|||||||
maximumFractionDigits: 0,
|
maximumFractionDigits: 0,
|
||||||
})}
|
})}
|
||||||
positiveTrend="down"
|
positiveTrend="down"
|
||||||
className="shrink-0 text-sm font-semibold"
|
className="text-sm font-semibold"
|
||||||
iconClassName="size-3.5"
|
iconClassName="size-3.5"
|
||||||
/>
|
/>
|
||||||
|
<span>vs. mês ant.</span>
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</li>
|
</li>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import Link from "next/link";
|
|||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { useMemo, useState } from "react";
|
import { useMemo, useState } from "react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
|
import { dashboardWidgetListStyles as styles } from "@/features/dashboard/components/dashboard-widget-list-styles";
|
||||||
import type { DashboardInboxSnapshot } from "@/features/dashboard/lib/inbox-snapshot-queries";
|
import type { DashboardInboxSnapshot } from "@/features/dashboard/lib/inbox-snapshot-queries";
|
||||||
import type { DashboardWidgetQuickActionOptions } from "@/features/dashboard/widget-registry/widget-config";
|
import type { DashboardWidgetQuickActionOptions } from "@/features/dashboard/widget-registry/widget-config";
|
||||||
import {
|
import {
|
||||||
@@ -201,8 +202,8 @@ export function InboxWidget({
|
|||||||
const displayLogo = logoSrc ?? DEFAULT_INBOX_APP_LOGO;
|
const displayLogo = logoSrc ?? DEFAULT_INBOX_APP_LOGO;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div key={item.id} className="flex items-center justify-between py-2">
|
<div key={item.id} className={styles.row}>
|
||||||
<div className="flex min-w-0 flex-1 items-center gap-2">
|
<div className={styles.main}>
|
||||||
<Image
|
<Image
|
||||||
src={displayLogo}
|
src={displayLogo}
|
||||||
alt={item.sourceAppName ?? ""}
|
alt={item.sourceAppName ?? ""}
|
||||||
@@ -212,24 +213,22 @@ export function InboxWidget({
|
|||||||
unoptimized
|
unoptimized
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<div className="min-w-0">
|
<div className={styles.textStack}>
|
||||||
<p className="truncate text-sm font-medium text-foreground">
|
<p className={styles.title}>{displayName}</p>
|
||||||
{displayName}
|
<div className={styles.meta}>
|
||||||
</p>
|
|
||||||
<div className="flex min-w-0 items-center gap-2 text-xs text-muted-foreground">
|
|
||||||
{item.sourceAppName && (
|
{item.sourceAppName && (
|
||||||
<span className="truncate">{item.sourceAppName}</span>
|
<span className="truncate">{item.sourceAppName}</span>
|
||||||
)}
|
)}
|
||||||
<span className="text-muted-foreground/60">
|
<span className="text-muted-foreground/60">
|
||||||
{relativeTime(item.notificationTimestamp)}
|
{relativeTime(item.createdAt)}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="ml-2 flex shrink-0 items-center gap-1">
|
<div className="ml-2 flex min-w-[7.5rem] shrink-0 items-center justify-end gap-1">
|
||||||
{amount !== null && (
|
{amount !== null && (
|
||||||
<MoneyValues className="font-medium" amount={amount} />
|
<MoneyValues className={styles.trailingValue} amount={amount} />
|
||||||
)}
|
)}
|
||||||
{amount === null && (
|
{amount === null && (
|
||||||
<span className="max-w-20 text-right text-xs leading-tight text-muted-foreground">
|
<span className="max-w-20 text-right text-xs leading-tight text-muted-foreground">
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import Image from "next/image";
|
|||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { useTransition } from "react";
|
import { useTransition } from "react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
|
import { dashboardWidgetListStyles as styles } from "@/features/dashboard/components/dashboard-widget-list-styles";
|
||||||
import type { DashboardAccount } from "@/features/dashboard/lib/accounts-queries";
|
import type { DashboardAccount } from "@/features/dashboard/lib/accounts-queries";
|
||||||
import { updateMyAccountsWidgetPreference } from "@/features/dashboard/widget-registry/widget-actions";
|
import { updateMyAccountsWidgetPreference } from "@/features/dashboard/widget-registry/widget-actions";
|
||||||
import MoneyValues from "@/shared/components/money-values";
|
import MoneyValues from "@/shared/components/money-values";
|
||||||
@@ -139,12 +140,9 @@ export function MyAccountsWidget({
|
|||||||
const logoSrc = resolveLogoSrc(account.logo);
|
const logoSrc = resolveLogoSrc(account.logo);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<li
|
<li key={account.id} className={styles.row}>
|
||||||
key={account.id}
|
<div className={styles.main}>
|
||||||
className="flex items-center justify-between py-1.5 transition-all duration-300"
|
<div className="relative flex size-9.5 shrink-0 items-center justify-center overflow-hidden rounded-full">
|
||||||
>
|
|
||||||
<div className="flex min-w-0 flex-1 items-center gap-2 py-1">
|
|
||||||
<div className="relative flex size-9.5 shrink-0 items-center justify-center overflow-hidden rounded-full bg-primary/10">
|
|
||||||
{logoSrc ? (
|
{logoSrc ? (
|
||||||
<Image
|
<Image
|
||||||
src={logoSrc}
|
src={logoSrc}
|
||||||
@@ -161,18 +159,18 @@ export function MyAccountsWidget({
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="min-w-0">
|
<div className={styles.textStack}>
|
||||||
<Link
|
<Link
|
||||||
prefetch
|
prefetch
|
||||||
href={`/accounts/${
|
href={`/accounts/${
|
||||||
account.id
|
account.id
|
||||||
}/statement?periodo=${formatPeriodForUrl(period)}`}
|
}/statement?periodo=${formatPeriodForUrl(period)}`}
|
||||||
className="inline-flex max-w-full items-center gap-1 text-sm font-medium text-foreground underline-offset-2 hover:text-primary hover:underline"
|
className={styles.titleLink}
|
||||||
>
|
>
|
||||||
<span className="truncate">{account.name}</span>
|
<span className="truncate">{account.name}</span>
|
||||||
</Link>
|
</Link>
|
||||||
|
|
||||||
<div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
|
<div className={styles.meta}>
|
||||||
<span className="truncate">{account.accountType}</span>
|
<span className="truncate">{account.accountType}</span>
|
||||||
{account.excludeFromBalance ? (
|
{account.excludeFromBalance ? (
|
||||||
<Tooltip>
|
<Tooltip>
|
||||||
@@ -195,10 +193,10 @@ export function MyAccountsWidget({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex flex-col items-end gap-0.5 text-right">
|
<div className={styles.trailing}>
|
||||||
<MoneyValues
|
<MoneyValues
|
||||||
className={cn(
|
className={cn(
|
||||||
"font-medium",
|
styles.trailingValue,
|
||||||
account.balance < 0 && "text-destructive",
|
account.balance < 0 && "text-destructive",
|
||||||
)}
|
)}
|
||||||
amount={account.balance}
|
amount={account.balance}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
import { RiGroupLine, RiVerifiedBadgeFill } from "@remixicon/react";
|
import { RiGroupLine, RiVerifiedBadgeFill } from "@remixicon/react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
|
import { dashboardWidgetListStyles as styles } from "@/features/dashboard/components/dashboard-widget-list-styles";
|
||||||
import { PercentageChangeIndicator } from "@/features/dashboard/components/percentage-change-indicator";
|
import { PercentageChangeIndicator } from "@/features/dashboard/components/percentage-change-indicator";
|
||||||
import type { DashboardPagador } from "@/features/dashboard/lib/payers-queries";
|
import type { DashboardPagador } from "@/features/dashboard/lib/payers-queries";
|
||||||
import MoneyValues from "@/shared/components/money-values";
|
import MoneyValues from "@/shared/components/money-values";
|
||||||
@@ -44,14 +45,9 @@ export function PayersWidget({ payers }: PayersWidgetProps) {
|
|||||||
: null;
|
: null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div key={payer.id} className={styles.row}>
|
||||||
key={payer.id}
|
<span className={styles.rank}>{index + 1}</span>
|
||||||
className="flex items-center justify-between gap-2 transition-all duration-300 py-1.5"
|
<div className={styles.main}>
|
||||||
>
|
|
||||||
<span className="w-3 shrink-0 text-left text-xs font-medium text-muted-foreground">
|
|
||||||
{index + 1}
|
|
||||||
</span>
|
|
||||||
<div className="flex min-w-0 flex-1 items-center gap-2 py-1">
|
|
||||||
<Avatar className="size-9.5 shrink-0">
|
<Avatar className="size-9.5 shrink-0">
|
||||||
<AvatarImage
|
<AvatarImage
|
||||||
src={getAvatarSrc(payer.avatarUrl)}
|
src={getAvatarSrc(payer.avatarUrl)}
|
||||||
@@ -60,11 +56,11 @@ export function PayersWidget({ payers }: PayersWidgetProps) {
|
|||||||
<AvatarFallback>{initials}</AvatarFallback>
|
<AvatarFallback>{initials}</AvatarFallback>
|
||||||
</Avatar>
|
</Avatar>
|
||||||
|
|
||||||
<div className="min-w-0">
|
<div className={styles.textStack}>
|
||||||
<Link
|
<Link
|
||||||
prefetch
|
prefetch
|
||||||
href={`/payers/${payer.id}`}
|
href={`/payers/${payer.id}`}
|
||||||
className="inline-flex max-w-full items-center gap-1 text-sm text-foreground underline-offset-2 hover:text-primary hover:underline"
|
className={styles.titleLink}
|
||||||
>
|
>
|
||||||
<span className="truncate font-medium">{payer.name}</span>
|
<span className="truncate font-medium">{payer.name}</span>
|
||||||
{payer.isAdmin && (
|
{payer.isAdmin && (
|
||||||
@@ -84,18 +80,18 @@ export function PayersWidget({ payers }: PayersWidgetProps) {
|
|||||||
</Tooltip>
|
</Tooltip>
|
||||||
)}
|
)}
|
||||||
</Link>
|
</Link>
|
||||||
<p className="truncate text-xs text-muted-foreground">
|
<p className={styles.meta}>Despesas no período</p>
|
||||||
Despesas no período
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex shrink-0 flex-col items-end">
|
<div className={styles.trailing}>
|
||||||
<MoneyValues
|
<MoneyValues
|
||||||
className="font-medium"
|
className={styles.trailingValue}
|
||||||
amount={payer.totalExpenses}
|
amount={payer.totalExpenses}
|
||||||
/>
|
/>
|
||||||
<div className="flex items-center gap-1 text-xs text-muted-foreground">
|
<div
|
||||||
|
className={`${styles.trailingMeta} text-muted-foreground`}
|
||||||
|
>
|
||||||
<PercentageChangeIndicator value={percentageChange} />
|
<PercentageChangeIndicator value={percentageChange} />
|
||||||
{percentageChange !== null ? (
|
{percentageChange !== null ? (
|
||||||
<span>vs. mês ant.</span>
|
<span>vs. mês ant.</span>
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
import { RiFileList2Line, RiStore3Line } from "@remixicon/react";
|
import { RiFileList2Line, RiStore3Line } from "@remixicon/react";
|
||||||
import { useEffect, useMemo, useRef, useState } from "react";
|
import { useEffect, useMemo, useRef, useState } from "react";
|
||||||
import type { PurchasesByCategoryData } from "@/features/dashboard/categories/purchases-by-category-queries";
|
import type { PurchasesByCategoryData } from "@/features/dashboard/categories/purchases-by-category-queries";
|
||||||
|
import { dashboardWidgetListStyles as styles } from "@/features/dashboard/components/dashboard-widget-list-styles";
|
||||||
import { EstablishmentLogo } from "@/shared/components/entity-avatar";
|
import { EstablishmentLogo } from "@/shared/components/entity-avatar";
|
||||||
import MoneyValues from "@/shared/components/money-values";
|
import MoneyValues from "@/shared/components/money-values";
|
||||||
import {
|
import {
|
||||||
@@ -162,26 +163,21 @@ export function PurchasesByCategoryWidget({
|
|||||||
<div className="flex flex-col">
|
<div className="flex flex-col">
|
||||||
{currentTransactions.map((transaction) => {
|
{currentTransactions.map((transaction) => {
|
||||||
return (
|
return (
|
||||||
<div
|
<div key={transaction.id} className={styles.row}>
|
||||||
key={transaction.id}
|
<div className={styles.main}>
|
||||||
className="flex items-center justify-between gap-2 transition-all duration-300 py-1.5"
|
|
||||||
>
|
|
||||||
<div className="flex min-w-0 flex-1 items-center gap-2">
|
|
||||||
<EstablishmentLogo name={transaction.name} size={37} />
|
<EstablishmentLogo name={transaction.name} size={37} />
|
||||||
|
|
||||||
<div className="min-w-0">
|
<div className={styles.textStack}>
|
||||||
<p className="truncate text-sm font-medium text-foreground">
|
<p className={styles.title}>{transaction.name}</p>
|
||||||
{transaction.name}
|
<p className={styles.meta}>
|
||||||
</p>
|
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
{formatTransactionDate(transaction.purchaseDate)}
|
{formatTransactionDate(transaction.purchaseDate)}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="shrink-0 text-foreground">
|
<div className={styles.trailing}>
|
||||||
<MoneyValues
|
<MoneyValues
|
||||||
className="font-medium"
|
className={styles.trailingValue}
|
||||||
amount={transaction.amount}
|
amount={transaction.amount}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { RiRefreshLine } from "@remixicon/react";
|
import { RiRefreshLine } from "@remixicon/react";
|
||||||
|
import { dashboardWidgetListStyles as styles } from "@/features/dashboard/components/dashboard-widget-list-styles";
|
||||||
import type { RecurringExpensesData } from "@/features/dashboard/expenses/recurring-expenses-queries";
|
import type { RecurringExpensesData } from "@/features/dashboard/expenses/recurring-expenses-queries";
|
||||||
import { EstablishmentLogo } from "@/shared/components/entity-avatar";
|
import { EstablishmentLogo } from "@/shared/components/entity-avatar";
|
||||||
import MoneyValues from "@/shared/components/money-values";
|
import MoneyValues from "@/shared/components/money-values";
|
||||||
@@ -36,26 +37,14 @@ export function RecurringExpensesWidget({
|
|||||||
.sort((a, b) => b.amount - a.amount)
|
.sort((a, b) => b.amount - a.amount)
|
||||||
.map((expense) => {
|
.map((expense) => {
|
||||||
return (
|
return (
|
||||||
<div
|
<div key={expense.id} className={styles.row}>
|
||||||
key={expense.id}
|
<div className={styles.main}>
|
||||||
className="flex items-center gap-2 transition-all duration-300 py-1.5"
|
|
||||||
>
|
|
||||||
<EstablishmentLogo name={expense.name} size={37} />
|
<EstablishmentLogo name={expense.name} size={37} />
|
||||||
|
|
||||||
<div className="min-w-0 flex-1">
|
<div className={styles.textStack}>
|
||||||
<div className="flex items-center justify-between">
|
<p className={styles.title}>{expense.name}</p>
|
||||||
<p className="truncate text-foreground text-sm font-medium">
|
<div className={styles.meta}>
|
||||||
{expense.name}
|
<span className="inline-flex min-w-0 items-center gap-1 [&_svg]:size-3.5">
|
||||||
</p>
|
|
||||||
|
|
||||||
<MoneyValues
|
|
||||||
className="font-medium"
|
|
||||||
amount={expense.amount}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex items-center justify-between text-xs text-muted-foreground">
|
|
||||||
<span className="inline-flex items-center gap-1 [&_svg]:size-3.5">
|
|
||||||
{getPaymentMethodIcon(expense.paymentMethod)}
|
{getPaymentMethodIcon(expense.paymentMethod)}
|
||||||
{expense.paymentMethod}
|
{expense.paymentMethod}
|
||||||
</span>
|
</span>
|
||||||
@@ -63,6 +52,14 @@ export function RecurringExpensesWidget({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div className={styles.trailing}>
|
||||||
|
<MoneyValues
|
||||||
|
className={styles.trailingValue}
|
||||||
|
amount={expense.amount}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { RiStore2Line } from "@remixicon/react";
|
import { RiStore2Line } from "@remixicon/react";
|
||||||
|
import { dashboardWidgetListStyles as styles } from "@/features/dashboard/components/dashboard-widget-list-styles";
|
||||||
import type { TopEstablishmentsData } from "@/features/dashboard/lib/top-establishments-queries";
|
import type { TopEstablishmentsData } from "@/features/dashboard/lib/top-establishments-queries";
|
||||||
import { EstablishmentLogo } from "@/shared/components/entity-avatar";
|
import { EstablishmentLogo } from "@/shared/components/entity-avatar";
|
||||||
import MoneyValues from "@/shared/components/money-values";
|
import MoneyValues from "@/shared/components/money-values";
|
||||||
@@ -30,30 +31,23 @@ export function TopEstablishmentsWidget({
|
|||||||
<div className="flex flex-col">
|
<div className="flex flex-col">
|
||||||
{data.establishments.map((establishment, index) => {
|
{data.establishments.map((establishment, index) => {
|
||||||
return (
|
return (
|
||||||
<div
|
<div key={establishment.id} className={styles.row}>
|
||||||
key={establishment.id}
|
<span className={styles.rank}>{index + 1}</span>
|
||||||
className="flex items-center justify-between gap-2 transition-all duration-300 py-1.5"
|
<div className={styles.main}>
|
||||||
>
|
|
||||||
<span className="w-3 shrink-0 text-left text-xs font-medium text-muted-foreground">
|
|
||||||
{index + 1}
|
|
||||||
</span>
|
|
||||||
<div className="flex min-w-0 flex-1 items-center gap-2">
|
|
||||||
<EstablishmentLogo name={establishment.name} size={37} />
|
<EstablishmentLogo name={establishment.name} size={37} />
|
||||||
|
|
||||||
<div className="min-w-0">
|
<div className={styles.textStack}>
|
||||||
<p className="truncate text-sm font-medium text-foreground">
|
<p className={styles.title}>{establishment.name}</p>
|
||||||
{establishment.name}
|
<p className={styles.meta}>
|
||||||
</p>
|
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
{formatOccurrencesLabel(establishment.occurrences)} ·
|
{formatOccurrencesLabel(establishment.occurrences)} ·
|
||||||
total acumulado
|
total acumulado
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="shrink-0 text-foreground">
|
<div className={styles.trailing}>
|
||||||
<MoneyValues
|
<MoneyValues
|
||||||
className="font-medium"
|
className={styles.trailingValue}
|
||||||
amount={establishment.amount}
|
amount={establishment.amount}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
import { RiArrowUpDoubleLine } from "@remixicon/react";
|
import { RiArrowUpDoubleLine } from "@remixicon/react";
|
||||||
import { useMemo } from "react";
|
import { useMemo } from "react";
|
||||||
|
import { dashboardWidgetListStyles as styles } from "@/features/dashboard/components/dashboard-widget-list-styles";
|
||||||
import type {
|
import type {
|
||||||
TopExpense,
|
TopExpense,
|
||||||
TopExpensesData,
|
TopExpensesData,
|
||||||
@@ -49,29 +50,22 @@ export function TopExpensesWidget({ data }: TopExpensesWidgetProps) {
|
|||||||
<div className="flex flex-col">
|
<div className="flex flex-col">
|
||||||
{expenses.map((expense, index) => {
|
{expenses.map((expense, index) => {
|
||||||
return (
|
return (
|
||||||
<div
|
<div key={expense.id} className={styles.row}>
|
||||||
key={expense.id}
|
<span className={styles.rank}>{index + 1}</span>
|
||||||
className="flex items-center justify-between gap-2 transition-all duration-300 py-1.5"
|
<div className={styles.main}>
|
||||||
>
|
|
||||||
<span className="w-3 shrink-0 text-left text-xs font-medium text-muted-foreground">
|
|
||||||
{index + 1}
|
|
||||||
</span>
|
|
||||||
<div className="flex min-w-0 flex-1 items-center gap-2">
|
|
||||||
<EstablishmentLogo name={expense.name} size={37} />
|
<EstablishmentLogo name={expense.name} size={37} />
|
||||||
|
|
||||||
<div className="min-w-0">
|
<div className={styles.textStack}>
|
||||||
<p className="truncate text-sm font-medium text-foreground">
|
<p className={styles.title}>{expense.name}</p>
|
||||||
{expense.name}
|
<p className={styles.meta}>
|
||||||
</p>
|
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
{formatTransactionDate(expense.purchaseDate)}
|
{formatTransactionDate(expense.purchaseDate)}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="shrink-0 text-foreground">
|
<div className={styles.trailing}>
|
||||||
<MoneyValues
|
<MoneyValues
|
||||||
className="font-medium"
|
className={styles.trailingValue}
|
||||||
amount={expense.amount}
|
amount={expense.amount}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -45,6 +45,7 @@ type InstallmentDetail = {
|
|||||||
export type InstallmentGroup = {
|
export type InstallmentGroup = {
|
||||||
seriesId: string;
|
seriesId: string;
|
||||||
name: string;
|
name: string;
|
||||||
|
note: string | null;
|
||||||
paymentMethod: string;
|
paymentMethod: string;
|
||||||
cardId: string | null;
|
cardId: string | null;
|
||||||
cartaoName: string | null;
|
cartaoName: string | null;
|
||||||
@@ -80,6 +81,7 @@ export async function fetchInstallmentAnalysis(
|
|||||||
id: transactions.id,
|
id: transactions.id,
|
||||||
seriesId: transactions.seriesId,
|
seriesId: transactions.seriesId,
|
||||||
name: transactions.name,
|
name: transactions.name,
|
||||||
|
note: transactions.note,
|
||||||
amount: transactions.amount,
|
amount: transactions.amount,
|
||||||
paymentMethod: transactions.paymentMethod,
|
paymentMethod: transactions.paymentMethod,
|
||||||
currentInstallment: transactions.currentInstallment,
|
currentInstallment: transactions.currentInstallment,
|
||||||
@@ -150,6 +152,7 @@ export async function fetchInstallmentAnalysis(
|
|||||||
seriesMap.set(row.seriesId, {
|
seriesMap.set(row.seriesId, {
|
||||||
seriesId: row.seriesId,
|
seriesId: row.seriesId,
|
||||||
name: row.name,
|
name: row.name,
|
||||||
|
note: row.note,
|
||||||
paymentMethod: row.paymentMethod,
|
paymentMethod: row.paymentMethod,
|
||||||
cardId: row.cardId,
|
cardId: row.cardId,
|
||||||
cartaoName: row.cartaoName,
|
cartaoName: row.cartaoName,
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ const mapDashboardNoteToNote = (note: DashboardNote): Note => ({
|
|||||||
tasks: note.tasks,
|
tasks: note.tasks,
|
||||||
archived: note.archived,
|
archived: note.archived,
|
||||||
createdAt: note.createdAt,
|
createdAt: note.createdAt,
|
||||||
|
attachments: [],
|
||||||
});
|
});
|
||||||
|
|
||||||
export const mapDashboardNotesToNotes = (notes: DashboardNote[]) =>
|
export const mapDashboardNotesToNotes = (notes: DashboardNote[]) =>
|
||||||
|
|||||||
@@ -174,9 +174,10 @@ export const widgetsConfig: WidgetConfig[] = [
|
|||||||
title: "Tendências de categorias",
|
title: "Tendências de categorias",
|
||||||
subtitle: "Top 10 maiores variações vs. mês anterior",
|
subtitle: "Top 10 maiores variações vs. mês anterior",
|
||||||
icon: <RiLineChartLine className="size-4" />,
|
icon: <RiLineChartLine className="size-4" />,
|
||||||
component: ({ data }) => (
|
component: ({ data, period }) => (
|
||||||
<CategoryTrendsWidget
|
<CategoryTrendsWidget
|
||||||
categories={data.expensesByCategoryData.categories}
|
categories={data.expensesByCategoryData.categories}
|
||||||
|
period={period}
|
||||||
/>
|
/>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -206,32 +206,32 @@ export function InvoiceSummaryCard({
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card className="gap-0 py-0">
|
<Card className="gap-0 py-0 space-y-2">
|
||||||
<CardContent className="px-4 py-4 sm:px-5 sm:py-5">
|
<CardContent className="px-4 py-4 sm:px-5 sm:py-5">
|
||||||
<div className="flex flex-col gap-4">
|
<div className="flex flex-col gap-4">
|
||||||
{/* Linha 1 — identidade */}
|
{/* Linha 1 — identidade */}
|
||||||
<div className="flex items-center justify-between gap-3">
|
<div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
|
||||||
<div className="flex min-w-0 items-center gap-3">
|
<div className="flex min-w-0 items-start gap-3">
|
||||||
{logoPath ? (
|
{logoPath ? (
|
||||||
<div className="flex size-12 shrink-0 items-center justify-center overflow-hidden rounded-full">
|
<div className="flex size-12 shrink-0 items-center justify-center overflow-hidden rounded-full">
|
||||||
<Image
|
<Image
|
||||||
src={logoPath}
|
src={logoPath}
|
||||||
alt={`Logo ${cardName}`}
|
alt={`Logo ${cardName}`}
|
||||||
width={42}
|
width={48}
|
||||||
height={42}
|
height={48}
|
||||||
className="h-full w-full object-contain"
|
className="h-full w-full object-contain"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
) : cardBrand ? (
|
) : cardBrand ? (
|
||||||
<span className="flex size-10 shrink-0 items-center justify-center rounded-full border bg-background text-xs font-medium text-muted-foreground">
|
<span className="flex size-12 shrink-0 items-center justify-center rounded-full border bg-card text-sm font-semibold text-primary">
|
||||||
{cardBrand.slice(0, 2).toUpperCase()}
|
{cardBrand.slice(0, 2).toUpperCase()}
|
||||||
</span>
|
</span>
|
||||||
) : null}
|
) : null}
|
||||||
<div className="min-w-0">
|
<div className="min-w-0 space-y-1">
|
||||||
<h2 className="truncate text-sm font-semibold text-foreground">
|
<h2 className="truncate text-xl font-semibold text-foreground sm:text-2xl">
|
||||||
{cardName}
|
{cardName}
|
||||||
</h2>
|
</h2>
|
||||||
<p className="text-xs text-muted-foreground">
|
<p className="text-sm leading-relaxed text-muted-foreground">
|
||||||
Fatura de {periodLabel}
|
Fatura de {periodLabel}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
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();
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
"use server";
|
"use server";
|
||||||
|
|
||||||
import { and, eq } from "drizzle-orm";
|
import { and, eq, inArray } from "drizzle-orm";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { notes } from "@/db/schema";
|
import { attachments, noteAttachments, notes } from "@/db/schema";
|
||||||
import {
|
import {
|
||||||
handleActionError,
|
handleActionError,
|
||||||
revalidateForEntity,
|
revalidateForEntity,
|
||||||
@@ -10,6 +10,7 @@ import {
|
|||||||
import { getUser } from "@/shared/lib/auth/server";
|
import { getUser } from "@/shared/lib/auth/server";
|
||||||
import { db } from "@/shared/lib/db";
|
import { db } from "@/shared/lib/db";
|
||||||
import { uuidSchema } from "@/shared/lib/schemas/common";
|
import { uuidSchema } from "@/shared/lib/schemas/common";
|
||||||
|
import { deleteS3Object } from "@/shared/lib/storage/presign";
|
||||||
import type { ActionResult } from "@/shared/lib/types/actions";
|
import type { ActionResult } from "@/shared/lib/types/actions";
|
||||||
|
|
||||||
const taskSchema = z.object({
|
const taskSchema = z.object({
|
||||||
@@ -70,25 +71,42 @@ type NoteDeleteInput = z.infer<typeof deleteNoteSchema>;
|
|||||||
|
|
||||||
export async function createNoteAction(
|
export async function createNoteAction(
|
||||||
input: NoteCreateInput,
|
input: NoteCreateInput,
|
||||||
): Promise<ActionResult> {
|
): Promise<ActionResult<{ noteId: string }>> {
|
||||||
try {
|
try {
|
||||||
const user = await getUser();
|
const user = await getUser();
|
||||||
const data = createNoteSchema.parse(input);
|
const data = createNoteSchema.parse(input);
|
||||||
|
|
||||||
await db.insert(notes).values({
|
const [created] = await db
|
||||||
|
.insert(notes)
|
||||||
|
.values({
|
||||||
title: data.title,
|
title: data.title,
|
||||||
description: data.description,
|
description: data.description,
|
||||||
type: data.type,
|
type: data.type,
|
||||||
tasks:
|
tasks:
|
||||||
data.tasks && data.tasks.length > 0 ? JSON.stringify(data.tasks) : null,
|
data.tasks && data.tasks.length > 0
|
||||||
|
? JSON.stringify(data.tasks)
|
||||||
|
: null,
|
||||||
userId: user.id,
|
userId: user.id,
|
||||||
});
|
})
|
||||||
|
.returning({ id: notes.id });
|
||||||
|
|
||||||
|
if (!created) {
|
||||||
|
return { success: false, error: "Não foi possível criar a anotação." };
|
||||||
|
}
|
||||||
|
|
||||||
revalidateForEntity("notes", user.id);
|
revalidateForEntity("notes", user.id);
|
||||||
|
|
||||||
return { success: true, message: "Anotação criada com sucesso." };
|
return {
|
||||||
|
success: true,
|
||||||
|
message: "Anotação criada com sucesso.",
|
||||||
|
data: { noteId: created.id },
|
||||||
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return handleActionError(error);
|
const result = handleActionError(error);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: result.success ? "Ocorreu um erro inesperado." : result.error,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -135,6 +153,25 @@ export async function deleteNoteAction(
|
|||||||
const user = await getUser();
|
const user = await getUser();
|
||||||
const data = deleteNoteSchema.parse(input);
|
const data = deleteNoteSchema.parse(input);
|
||||||
|
|
||||||
|
const linkedAttachments = await db
|
||||||
|
.select({ id: attachments.id, fileKey: attachments.fileKey })
|
||||||
|
.from(noteAttachments)
|
||||||
|
.innerJoin(
|
||||||
|
attachments,
|
||||||
|
and(
|
||||||
|
eq(noteAttachments.attachmentId, attachments.id),
|
||||||
|
eq(attachments.userId, user.id),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.innerJoin(
|
||||||
|
notes,
|
||||||
|
and(
|
||||||
|
eq(noteAttachments.noteId, notes.id),
|
||||||
|
eq(notes.id, data.id),
|
||||||
|
eq(notes.userId, user.id),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
const [deleted] = await db
|
const [deleted] = await db
|
||||||
.delete(notes)
|
.delete(notes)
|
||||||
.where(and(eq(notes.id, data.id), eq(notes.userId, user.id)))
|
.where(and(eq(notes.id, data.id), eq(notes.userId, user.id)))
|
||||||
@@ -147,6 +184,23 @@ export async function deleteNoteAction(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (linkedAttachments.length > 0) {
|
||||||
|
await Promise.all(
|
||||||
|
linkedAttachments.map((attachment) =>
|
||||||
|
deleteS3Object(attachment.fileKey),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await db.delete(attachments).where(
|
||||||
|
and(
|
||||||
|
eq(attachments.userId, user.id),
|
||||||
|
inArray(
|
||||||
|
attachments.id,
|
||||||
|
linkedAttachments.map((attachment) => attachment.id),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
revalidateForEntity("notes", user.id);
|
revalidateForEntity("notes", user.id);
|
||||||
|
|
||||||
return { success: true, message: "Anotação removida com sucesso." };
|
return { success: true, message: "Anotação removida com sucesso." };
|
||||||
|
|||||||
279
src/features/notes/actions/attachments.ts
Normal file
@@ -0,0 +1,279 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import crypto, { randomUUID } from "node:crypto";
|
||||||
|
import { and, eq } from "drizzle-orm";
|
||||||
|
import { z } from "zod/v4";
|
||||||
|
import {
|
||||||
|
attachments,
|
||||||
|
noteAttachments,
|
||||||
|
notes,
|
||||||
|
userPreferences,
|
||||||
|
} from "@/db/schema";
|
||||||
|
import {
|
||||||
|
handleActionError,
|
||||||
|
revalidateForEntity,
|
||||||
|
} from "@/shared/lib/actions/helpers";
|
||||||
|
import {
|
||||||
|
ALLOWED_MIME_TYPES,
|
||||||
|
ATTACHMENT_SIZE_OPTIONS,
|
||||||
|
} from "@/shared/lib/attachments/config";
|
||||||
|
import { getUser } from "@/shared/lib/auth/server";
|
||||||
|
import { db } from "@/shared/lib/db";
|
||||||
|
import {
|
||||||
|
createPresignedPutUrl,
|
||||||
|
deleteS3Object,
|
||||||
|
headS3Object,
|
||||||
|
} from "@/shared/lib/storage/presign";
|
||||||
|
import type { ActionResult } from "@/shared/lib/types/actions";
|
||||||
|
|
||||||
|
const UPLOAD_TOKEN_EXPIRY_SECONDS = 10 * 60;
|
||||||
|
const MAX_NOTE_FILE_SIZE = Math.max(...ATTACHMENT_SIZE_OPTIONS) * 1024 * 1024;
|
||||||
|
|
||||||
|
const presignSchema = z.object({
|
||||||
|
noteId: z.string().uuid(),
|
||||||
|
fileName: z.string().min(1).max(255),
|
||||||
|
mimeType: z.enum(ALLOWED_MIME_TYPES),
|
||||||
|
fileSize: z.number().positive().max(MAX_NOTE_FILE_SIZE),
|
||||||
|
});
|
||||||
|
|
||||||
|
const tokenPayloadSchema = presignSchema.extend({
|
||||||
|
userId: z.string().min(1),
|
||||||
|
fileKey: z.string().min(1),
|
||||||
|
exp: z.number().int(),
|
||||||
|
});
|
||||||
|
|
||||||
|
type UploadTokenPayload = z.infer<typeof tokenPayloadSchema>;
|
||||||
|
|
||||||
|
type PresignResult =
|
||||||
|
| { success: true; presignedUrl: string; uploadToken: string }
|
||||||
|
| { success: false; error: string };
|
||||||
|
|
||||||
|
export type NoteAttachmentData = {
|
||||||
|
attachmentId: string;
|
||||||
|
fileName: string;
|
||||||
|
fileSize: number;
|
||||||
|
mimeType: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
function getUploadTokenSecret(): string {
|
||||||
|
const secret = process.env.BETTER_AUTH_SECRET;
|
||||||
|
if (!secret) throw new Error("BETTER_AUTH_SECRET is required.");
|
||||||
|
return secret;
|
||||||
|
}
|
||||||
|
|
||||||
|
function encode(value: string): string {
|
||||||
|
return Buffer.from(value).toString("base64url");
|
||||||
|
}
|
||||||
|
|
||||||
|
function signUploadToken(payload: UploadTokenPayload): string {
|
||||||
|
const encoded = encode(JSON.stringify(payload));
|
||||||
|
const signature = crypto
|
||||||
|
.createHmac("sha256", getUploadTokenSecret())
|
||||||
|
.update(encoded)
|
||||||
|
.digest("base64url");
|
||||||
|
return `${encoded}.${signature}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function verifyUploadToken(token: string): UploadTokenPayload | null {
|
||||||
|
try {
|
||||||
|
const [encoded, signature] = token.split(".");
|
||||||
|
if (!encoded || !signature) return null;
|
||||||
|
const expected = crypto
|
||||||
|
.createHmac("sha256", getUploadTokenSecret())
|
||||||
|
.update(encoded)
|
||||||
|
.digest("base64url");
|
||||||
|
if (
|
||||||
|
signature.length !== expected.length ||
|
||||||
|
!crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected))
|
||||||
|
) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const parsed = tokenPayloadSchema.safeParse(
|
||||||
|
JSON.parse(Buffer.from(encoded, "base64url").toString("utf8")),
|
||||||
|
);
|
||||||
|
if (!parsed.success || parsed.data.exp < Math.floor(Date.now() / 1000)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (!parsed.data.fileKey.startsWith(`${parsed.data.userId}/`)) return null;
|
||||||
|
return parsed.data;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function findOwnedNote(noteId: string, userId: string) {
|
||||||
|
const [note] = await db
|
||||||
|
.select({ id: notes.id, type: notes.type })
|
||||||
|
.from(notes)
|
||||||
|
.where(and(eq(notes.id, noteId), eq(notes.userId, userId)));
|
||||||
|
return note?.type === "nota" ? note : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getAttachmentLimitBytes(userId: string): Promise<number> {
|
||||||
|
const [preferences] = await db
|
||||||
|
.select({ maxSizeMb: userPreferences.attachmentMaxSizeMb })
|
||||||
|
.from(userPreferences)
|
||||||
|
.where(eq(userPreferences.userId, userId));
|
||||||
|
return (preferences?.maxSizeMb ?? 50) * 1024 * 1024;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getPresignedNoteAttachmentUploadUrlAction(input: {
|
||||||
|
noteId: string;
|
||||||
|
fileName: string;
|
||||||
|
mimeType: string;
|
||||||
|
fileSize: number;
|
||||||
|
}): Promise<PresignResult> {
|
||||||
|
try {
|
||||||
|
const user = await getUser();
|
||||||
|
const data = presignSchema.parse(input);
|
||||||
|
if (data.fileSize > (await getAttachmentLimitBytes(user.id))) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "O arquivo excede o limite configurado para anexos.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (!(await findOwnedNote(data.noteId, user.id))) {
|
||||||
|
return { success: false, error: "Nota não encontrada." };
|
||||||
|
}
|
||||||
|
|
||||||
|
const extensions: Record<(typeof ALLOWED_MIME_TYPES)[number], string> = {
|
||||||
|
"application/pdf": "pdf",
|
||||||
|
"image/jpeg": "jpg",
|
||||||
|
"image/png": "png",
|
||||||
|
"image/webp": "webp",
|
||||||
|
};
|
||||||
|
const extension = extensions[data.mimeType];
|
||||||
|
const fileKey = `${user.id}/${randomUUID()}.${extension}`;
|
||||||
|
const presignedUrl = await createPresignedPutUrl(fileKey, data.mimeType);
|
||||||
|
const uploadToken = signUploadToken({
|
||||||
|
...data,
|
||||||
|
userId: user.id,
|
||||||
|
fileKey,
|
||||||
|
exp: Math.floor(Date.now() / 1000) + UPLOAD_TOKEN_EXPIRY_SECONDS,
|
||||||
|
});
|
||||||
|
return { success: true, presignedUrl, uploadToken };
|
||||||
|
} catch (error) {
|
||||||
|
const result = handleActionError(error);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: result.success ? "Algo deu errado." : result.error,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function confirmNoteAttachmentUploadAction(input: {
|
||||||
|
uploadToken: string;
|
||||||
|
}): Promise<ActionResult<NoteAttachmentData>> {
|
||||||
|
try {
|
||||||
|
const user = await getUser();
|
||||||
|
const payload = verifyUploadToken(input.uploadToken);
|
||||||
|
if (!payload || payload.userId !== user.id) {
|
||||||
|
return { success: false, error: "Upload de anexo inválido ou expirado." };
|
||||||
|
}
|
||||||
|
if (!(await findOwnedNote(payload.noteId, user.id))) {
|
||||||
|
return { success: false, error: "Nota não encontrada." };
|
||||||
|
}
|
||||||
|
|
||||||
|
const metadata = await headS3Object(payload.fileKey);
|
||||||
|
if (
|
||||||
|
!metadata.contentLength ||
|
||||||
|
metadata.contentLength !== payload.fileSize ||
|
||||||
|
metadata.contentLength > MAX_NOTE_FILE_SIZE ||
|
||||||
|
metadata.contentType !== payload.mimeType
|
||||||
|
) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "O arquivo enviado não confere com o upload autorizado.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const [attachment] = await db
|
||||||
|
.insert(attachments)
|
||||||
|
.values({
|
||||||
|
userId: user.id,
|
||||||
|
fileKey: payload.fileKey,
|
||||||
|
fileName: payload.fileName,
|
||||||
|
fileSize: payload.fileSize,
|
||||||
|
mimeType: payload.mimeType,
|
||||||
|
})
|
||||||
|
.returning({ id: attachments.id });
|
||||||
|
if (!attachment)
|
||||||
|
return { success: false, error: "Não foi possível salvar o anexo." };
|
||||||
|
|
||||||
|
await db.insert(noteAttachments).values({
|
||||||
|
noteId: payload.noteId,
|
||||||
|
attachmentId: attachment.id,
|
||||||
|
});
|
||||||
|
revalidateForEntity("notes", user.id);
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: "Anexo enviado.",
|
||||||
|
data: {
|
||||||
|
attachmentId: attachment.id,
|
||||||
|
fileName: payload.fileName,
|
||||||
|
fileSize: payload.fileSize,
|
||||||
|
mimeType: payload.mimeType,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
const result = handleActionError(error);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: result.success ? "Ocorreu um erro inesperado." : result.error,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function removeNoteAttachmentAction(input: {
|
||||||
|
noteId: string;
|
||||||
|
attachmentId: string;
|
||||||
|
}): Promise<ActionResult> {
|
||||||
|
try {
|
||||||
|
const user = await getUser();
|
||||||
|
const data = z
|
||||||
|
.object({ noteId: z.string().uuid(), attachmentId: z.string().uuid() })
|
||||||
|
.parse(input);
|
||||||
|
if (!(await findOwnedNote(data.noteId, user.id))) {
|
||||||
|
return { success: false, error: "Nota não encontrada." };
|
||||||
|
}
|
||||||
|
const [attachment] = await db
|
||||||
|
.select({ fileKey: attachments.fileKey })
|
||||||
|
.from(noteAttachments)
|
||||||
|
.innerJoin(
|
||||||
|
attachments,
|
||||||
|
and(
|
||||||
|
eq(noteAttachments.attachmentId, attachments.id),
|
||||||
|
eq(attachments.userId, user.id),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(noteAttachments.noteId, data.noteId),
|
||||||
|
eq(noteAttachments.attachmentId, data.attachmentId),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
if (!attachment) return { success: false, error: "Anexo não encontrado." };
|
||||||
|
|
||||||
|
await db
|
||||||
|
.delete(noteAttachments)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(noteAttachments.noteId, data.noteId),
|
||||||
|
eq(noteAttachments.attachmentId, data.attachmentId),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await deleteS3Object(attachment.fileKey);
|
||||||
|
await db
|
||||||
|
.delete(attachments)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(attachments.id, data.attachmentId),
|
||||||
|
eq(attachments.userId, user.id),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
revalidateForEntity("notes", user.id);
|
||||||
|
return { success: true, message: "Anexo removido." };
|
||||||
|
} catch (error) {
|
||||||
|
return handleActionError(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
345
src/features/notes/components/note-attachments-field.tsx
Normal file
@@ -0,0 +1,345 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import {
|
||||||
|
RiAttachment2,
|
||||||
|
RiCloseLine,
|
||||||
|
RiDeleteBinLine,
|
||||||
|
RiDownloadLine,
|
||||||
|
RiFileImageLine,
|
||||||
|
RiFilePdf2Line,
|
||||||
|
} from "@remixicon/react";
|
||||||
|
import { useRef, useState } from "react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import {
|
||||||
|
confirmNoteAttachmentUploadAction,
|
||||||
|
getPresignedNoteAttachmentUploadUrlAction,
|
||||||
|
removeNoteAttachmentAction,
|
||||||
|
} from "@/features/notes/actions/attachments";
|
||||||
|
import type { NoteAttachment } from "@/features/notes/components/types";
|
||||||
|
import { Button } from "@/shared/components/ui/button";
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogClose,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from "@/shared/components/ui/dialog";
|
||||||
|
import {
|
||||||
|
ALLOWED_MIME_TYPES,
|
||||||
|
DEFAULT_MAX_FILE_SIZE_MB,
|
||||||
|
} from "@/shared/lib/attachments/config";
|
||||||
|
|
||||||
|
type UploadResult =
|
||||||
|
| { success: true; attachment: NoteAttachment }
|
||||||
|
| { success: false; error: string };
|
||||||
|
|
||||||
|
export async function uploadNoteAttachment(
|
||||||
|
noteId: string,
|
||||||
|
file: File,
|
||||||
|
): Promise<UploadResult> {
|
||||||
|
try {
|
||||||
|
const presign = await getPresignedNoteAttachmentUploadUrlAction({
|
||||||
|
noteId,
|
||||||
|
fileName: file.name,
|
||||||
|
fileSize: file.size,
|
||||||
|
mimeType: file.type,
|
||||||
|
});
|
||||||
|
if (!presign.success) return presign;
|
||||||
|
|
||||||
|
const uploaded = await fetch(presign.presignedUrl, {
|
||||||
|
method: "PUT",
|
||||||
|
body: file,
|
||||||
|
headers: { "Content-Type": file.type },
|
||||||
|
});
|
||||||
|
if (!uploaded.ok) {
|
||||||
|
return { success: false, error: "Não foi possível enviar o arquivo." };
|
||||||
|
}
|
||||||
|
|
||||||
|
const confirmed = await confirmNoteAttachmentUploadAction({
|
||||||
|
uploadToken: presign.uploadToken,
|
||||||
|
});
|
||||||
|
if (!confirmed.success || !confirmed.data) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: confirmed.success
|
||||||
|
? "Não foi possível salvar o anexo."
|
||||||
|
: confirmed.error,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return { success: true, attachment: confirmed.data };
|
||||||
|
} catch {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Não foi possível enviar o arquivo agora.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatBytes(bytes: number): string {
|
||||||
|
if (bytes < 1024) return `${bytes} B`;
|
||||||
|
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
||||||
|
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateFile(file: File, maxSizeMb: number): string | null {
|
||||||
|
if (
|
||||||
|
!ALLOWED_MIME_TYPES.includes(
|
||||||
|
file.type as (typeof ALLOWED_MIME_TYPES)[number],
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
return "Tipo não suportado. Use PDF, JPEG, PNG ou WebP.";
|
||||||
|
}
|
||||||
|
if (file.size > maxSizeMb * 1024 * 1024) {
|
||||||
|
return `O arquivo deve ter no máximo ${maxSizeMb}MB.`;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface NoteAttachmentsFieldProps {
|
||||||
|
noteId?: string;
|
||||||
|
attachments: NoteAttachment[];
|
||||||
|
pendingFiles: File[];
|
||||||
|
onAttachmentsChange: (attachments: NoteAttachment[]) => void;
|
||||||
|
onPendingFilesChange: (files: File[]) => void;
|
||||||
|
onBusyChange?: (busy: boolean) => void;
|
||||||
|
maxSizeMb?: number;
|
||||||
|
disabled?: boolean;
|
||||||
|
readonly?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function NoteAttachmentsField({
|
||||||
|
noteId,
|
||||||
|
attachments,
|
||||||
|
pendingFiles,
|
||||||
|
onAttachmentsChange,
|
||||||
|
onPendingFilesChange,
|
||||||
|
onBusyChange,
|
||||||
|
maxSizeMb = DEFAULT_MAX_FILE_SIZE_MB,
|
||||||
|
disabled = false,
|
||||||
|
readonly = false,
|
||||||
|
}: NoteAttachmentsFieldProps) {
|
||||||
|
const inputRef = useRef<HTMLInputElement>(null);
|
||||||
|
const [uploading, setUploading] = useState(false);
|
||||||
|
const [removing, setRemoving] = useState<NoteAttachment | null>(null);
|
||||||
|
const [isRemoving, setIsRemoving] = useState(false);
|
||||||
|
const [openingId, setOpeningId] = useState<string | null>(null);
|
||||||
|
|
||||||
|
async function addFiles(files: File[]) {
|
||||||
|
const valid: File[] = [];
|
||||||
|
for (const file of files) {
|
||||||
|
const error = validateFile(file, maxSizeMb);
|
||||||
|
if (error) toast.error(`${file.name}: ${error}`);
|
||||||
|
else valid.push(file);
|
||||||
|
}
|
||||||
|
if (valid.length === 0) return;
|
||||||
|
|
||||||
|
if (!noteId) {
|
||||||
|
onPendingFilesChange([...pendingFiles, ...valid]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setUploading(true);
|
||||||
|
onBusyChange?.(true);
|
||||||
|
const added: NoteAttachment[] = [];
|
||||||
|
for (const file of valid) {
|
||||||
|
const result = await uploadNoteAttachment(noteId, file);
|
||||||
|
if (result.success) added.push(result.attachment);
|
||||||
|
else toast.error(`${file.name}: ${result.error}`);
|
||||||
|
}
|
||||||
|
setUploading(false);
|
||||||
|
onBusyChange?.(false);
|
||||||
|
if (added.length > 0) {
|
||||||
|
onAttachmentsChange([...attachments, ...added]);
|
||||||
|
toast.success(
|
||||||
|
added.length === 1
|
||||||
|
? "Anexo enviado."
|
||||||
|
: `${added.length} anexos enviados.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function downloadAttachment(attachment: NoteAttachment) {
|
||||||
|
setOpeningId(attachment.attachmentId);
|
||||||
|
try {
|
||||||
|
const response = await fetch(
|
||||||
|
`/api/attachments/${attachment.attachmentId}/presign`,
|
||||||
|
);
|
||||||
|
if (!response.ok) throw new Error();
|
||||||
|
const { url } = (await response.json()) as { url: string };
|
||||||
|
const anchor = document.createElement("a");
|
||||||
|
anchor.href = url;
|
||||||
|
anchor.download = attachment.fileName;
|
||||||
|
anchor.target = "_blank";
|
||||||
|
anchor.rel = "noreferrer";
|
||||||
|
anchor.click();
|
||||||
|
} catch {
|
||||||
|
toast.error("Não foi possível baixar o anexo agora.");
|
||||||
|
} finally {
|
||||||
|
setOpeningId(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function confirmRemove() {
|
||||||
|
if (!noteId || !removing) return;
|
||||||
|
setIsRemoving(true);
|
||||||
|
onBusyChange?.(true);
|
||||||
|
const result = await removeNoteAttachmentAction({
|
||||||
|
noteId,
|
||||||
|
attachmentId: removing.attachmentId,
|
||||||
|
});
|
||||||
|
setIsRemoving(false);
|
||||||
|
onBusyChange?.(false);
|
||||||
|
if (result.success) {
|
||||||
|
onAttachmentsChange(
|
||||||
|
attachments.filter(
|
||||||
|
(item) => item.attachmentId !== removing.attachmentId,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
setRemoving(null);
|
||||||
|
toast.success(result.message);
|
||||||
|
} else {
|
||||||
|
toast.error(result.error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<p className="text-xs font-medium">Anexos</p>
|
||||||
|
<input
|
||||||
|
ref={inputRef}
|
||||||
|
type="file"
|
||||||
|
multiple
|
||||||
|
className="hidden"
|
||||||
|
accept={ALLOWED_MIME_TYPES.join(",")}
|
||||||
|
onChange={(event) => {
|
||||||
|
void addFiles(Array.from(event.target.files ?? []));
|
||||||
|
event.target.value = "";
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{attachments.length > 0 && (
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
{attachments.map((attachment) => (
|
||||||
|
<div
|
||||||
|
key={attachment.attachmentId}
|
||||||
|
className="flex min-w-0 items-center gap-2 rounded-md border px-3 py-2 text-sm"
|
||||||
|
>
|
||||||
|
{attachment.mimeType === "application/pdf" ? (
|
||||||
|
<RiFilePdf2Line className="size-4 shrink-0 text-red-500" />
|
||||||
|
) : (
|
||||||
|
<RiFileImageLine className="size-4 shrink-0 text-blue-500" />
|
||||||
|
)}
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<p className="truncate font-medium" title={attachment.fileName}>
|
||||||
|
{attachment.fileName}
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
{formatBytes(attachment.fileSize)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className="size-7 shrink-0"
|
||||||
|
disabled={openingId === attachment.attachmentId}
|
||||||
|
onClick={() => void downloadAttachment(attachment)}
|
||||||
|
aria-label={`Baixar ${attachment.fileName}`}
|
||||||
|
>
|
||||||
|
<RiDownloadLine className="size-4" />
|
||||||
|
</Button>
|
||||||
|
{!readonly && (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className="size-7 shrink-0 text-destructive hover:text-destructive"
|
||||||
|
disabled={disabled}
|
||||||
|
onClick={() => setRemoving(attachment)}
|
||||||
|
aria-label={`Remover ${attachment.fileName}`}
|
||||||
|
>
|
||||||
|
<RiDeleteBinLine className="size-4" />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{pendingFiles.map((file, index) => (
|
||||||
|
<div
|
||||||
|
key={`${file.name}-${file.size}-${file.lastModified}-${index}`}
|
||||||
|
className="flex min-w-0 items-center gap-2 rounded-md border border-dashed px-3 py-2 text-sm"
|
||||||
|
>
|
||||||
|
<RiAttachment2 className="size-4 shrink-0 text-muted-foreground" />
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<p className="truncate font-medium">{file.name}</p>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
Será enviado ao salvar
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className="size-7 shrink-0"
|
||||||
|
onClick={() =>
|
||||||
|
onPendingFilesChange(
|
||||||
|
pendingFiles.filter((_, fileIndex) => fileIndex !== index),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
aria-label={`Cancelar ${file.name}`}
|
||||||
|
>
|
||||||
|
<RiCloseLine className="size-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
|
||||||
|
{!readonly && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="flex min-h-16 w-full items-center justify-center gap-2 rounded-md border border-dashed px-3 text-sm text-muted-foreground transition-colors hover:border-foreground/40 hover:text-foreground disabled:pointer-events-none disabled:opacity-50"
|
||||||
|
onClick={() => inputRef.current?.click()}
|
||||||
|
disabled={disabled || uploading}
|
||||||
|
>
|
||||||
|
<RiAttachment2 className="size-4" />
|
||||||
|
<span>{uploading ? "Enviando..." : "Adicionar anexos"}</span>
|
||||||
|
<span className="hidden text-xs sm:inline">
|
||||||
|
PDF ou imagem · máx. {maxSizeMb} MB
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Dialog
|
||||||
|
open={Boolean(removing)}
|
||||||
|
onOpenChange={(open) => !open && setRemoving(null)}
|
||||||
|
>
|
||||||
|
<DialogContent className="sm:max-w-sm">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Remover anexo?</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
O arquivo {removing?.fileName} será removido desta nota.
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<DialogFooter>
|
||||||
|
<DialogClose asChild>
|
||||||
|
<Button type="button" variant="outline" disabled={isRemoving}>
|
||||||
|
Cancelar
|
||||||
|
</Button>
|
||||||
|
</DialogClose>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="destructive"
|
||||||
|
disabled={isRemoving}
|
||||||
|
onClick={() => void confirmRemove()}
|
||||||
|
>
|
||||||
|
{isRemoving ? "Removendo..." : "Remover"}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
import {
|
import {
|
||||||
RiArchiveLine,
|
RiArchiveLine,
|
||||||
|
RiAttachment2,
|
||||||
RiCheckLine,
|
RiCheckLine,
|
||||||
RiDeleteBin5Line,
|
RiDeleteBin5Line,
|
||||||
RiFileList2Line,
|
RiFileList2Line,
|
||||||
@@ -87,11 +88,19 @@ export function NoteCard({
|
|||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
<div className="flex shrink-0 flex-col items-end gap-1.5">
|
||||||
{isTask && (
|
{isTask && (
|
||||||
<Badge variant="outline" className="shrink-0 text-xs">
|
<Badge variant="outline" className="shrink-0 text-xs">
|
||||||
{completedCount}/{totalCount} concluídas
|
{completedCount}/{totalCount} concluídas
|
||||||
</Badge>
|
</Badge>
|
||||||
)}
|
)}
|
||||||
|
{!isTask && note.attachments.length > 0 && (
|
||||||
|
<Badge variant="outline" className="gap-1 text-xs">
|
||||||
|
<RiAttachment2 className="size-3.5" />
|
||||||
|
{note.attachments.length}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{isTask ? (
|
{isTask ? (
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { RiCheckLine, RiSubtractLine } from "@remixicon/react";
|
import { RiCheckLine, RiSubtractLine } from "@remixicon/react";
|
||||||
|
import { NoteAttachmentsField } from "@/features/notes/components/note-attachments-field";
|
||||||
import {
|
import {
|
||||||
buildNoteDisplayTitle,
|
buildNoteDisplayTitle,
|
||||||
formatNoteCreatedAtLong,
|
formatNoteCreatedAtLong,
|
||||||
@@ -85,9 +86,21 @@ export function NoteDetailsDialog({
|
|||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="max-h-[320px] overflow-auto whitespace-pre-line wrap-break-word text-sm text-foreground">
|
<div className="max-h-[55vh] space-y-4 overflow-auto">
|
||||||
|
<div className="whitespace-pre-line wrap-break-word text-sm text-foreground">
|
||||||
{note.description}
|
{note.description}
|
||||||
</div>
|
</div>
|
||||||
|
{note.attachments.length > 0 && (
|
||||||
|
<NoteAttachmentsField
|
||||||
|
noteId={note.id}
|
||||||
|
attachments={note.attachments}
|
||||||
|
pendingFiles={[]}
|
||||||
|
onAttachmentsChange={() => undefined}
|
||||||
|
onPendingFilesChange={() => undefined}
|
||||||
|
readonly
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<DialogFooter>
|
<DialogFooter>
|
||||||
|
|||||||
@@ -15,6 +15,10 @@ import {
|
|||||||
} from "react";
|
} from "react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import { createNoteAction, updateNoteAction } from "@/features/notes/actions";
|
import { createNoteAction, updateNoteAction } from "@/features/notes/actions";
|
||||||
|
import {
|
||||||
|
NoteAttachmentsField,
|
||||||
|
uploadNoteAttachment,
|
||||||
|
} from "@/features/notes/components/note-attachments-field";
|
||||||
import { Button } from "@/shared/components/ui/button";
|
import { Button } from "@/shared/components/ui/button";
|
||||||
import { Checkbox } from "@/shared/components/ui/checkbox";
|
import { Checkbox } from "@/shared/components/ui/checkbox";
|
||||||
import {
|
import {
|
||||||
@@ -34,6 +38,7 @@ import { useFormState } from "@/shared/hooks/use-form-state";
|
|||||||
import { cn } from "@/shared/utils/ui";
|
import { cn } from "@/shared/utils/ui";
|
||||||
import {
|
import {
|
||||||
type Note,
|
type Note,
|
||||||
|
type NoteAttachment,
|
||||||
type NoteFormValues,
|
type NoteFormValues,
|
||||||
sortTasksByStatus,
|
sortTasksByStatus,
|
||||||
type Task,
|
type Task,
|
||||||
@@ -46,6 +51,7 @@ interface NoteDialogProps {
|
|||||||
note?: Note;
|
note?: Note;
|
||||||
open?: boolean;
|
open?: boolean;
|
||||||
onOpenChange?: (open: boolean) => void;
|
onOpenChange?: (open: boolean) => void;
|
||||||
|
attachmentMaxSizeMb?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
const MAX_TITLE = 30;
|
const MAX_TITLE = 30;
|
||||||
@@ -69,12 +75,16 @@ export function NoteDialog({
|
|||||||
note,
|
note,
|
||||||
open,
|
open,
|
||||||
onOpenChange,
|
onOpenChange,
|
||||||
|
attachmentMaxSizeMb,
|
||||||
}: NoteDialogProps) {
|
}: NoteDialogProps) {
|
||||||
const [isPending, startTransition] = useTransition();
|
const [isPending, startTransition] = useTransition();
|
||||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||||
const [newTaskText, setNewTaskText] = useState("");
|
const [newTaskText, setNewTaskText] = useState("");
|
||||||
const [editingTaskId, setEditingTaskId] = useState<string | null>(null);
|
const [editingTaskId, setEditingTaskId] = useState<string | null>(null);
|
||||||
const [editingTaskText, setEditingTaskText] = useState("");
|
const [editingTaskText, setEditingTaskText] = useState("");
|
||||||
|
const [noteAttachments, setNoteAttachments] = useState<NoteAttachment[]>([]);
|
||||||
|
const [pendingFiles, setPendingFiles] = useState<File[]>([]);
|
||||||
|
const [isAttachmentPending, setIsAttachmentPending] = useState(false);
|
||||||
|
|
||||||
const titleRef = useRef<HTMLInputElement>(null);
|
const titleRef = useRef<HTMLInputElement>(null);
|
||||||
const descRef = useRef<HTMLTextAreaElement>(null);
|
const descRef = useRef<HTMLTextAreaElement>(null);
|
||||||
@@ -99,6 +109,9 @@ export function NoteDialog({
|
|||||||
setNewTaskText("");
|
setNewTaskText("");
|
||||||
setEditingTaskId(null);
|
setEditingTaskId(null);
|
||||||
setEditingTaskText("");
|
setEditingTaskText("");
|
||||||
|
setNoteAttachments(note?.attachments ?? []);
|
||||||
|
setPendingFiles([]);
|
||||||
|
setIsAttachmentPending(false);
|
||||||
requestAnimationFrame(() => titleRef.current?.focus());
|
requestAnimationFrame(() => titleRef.current?.focus());
|
||||||
}
|
}
|
||||||
}, [dialogOpen, note, resetForm]);
|
}, [dialogOpen, note, resetForm]);
|
||||||
@@ -137,12 +150,14 @@ export function NoteDialog({
|
|||||||
|
|
||||||
const disableSubmit =
|
const disableSubmit =
|
||||||
isPending ||
|
isPending ||
|
||||||
|
isAttachmentPending ||
|
||||||
onlySpaces ||
|
onlySpaces ||
|
||||||
unchanged ||
|
unchanged ||
|
||||||
invalidLen ||
|
invalidLen ||
|
||||||
Boolean(editingTaskId);
|
Boolean(editingTaskId);
|
||||||
|
|
||||||
const handleOpenChange = (v: boolean) => {
|
const handleOpenChange = (v: boolean) => {
|
||||||
|
if (!v && (isPending || isAttachmentPending)) return;
|
||||||
setDialogOpen(v);
|
setDialogOpen(v);
|
||||||
if (!v) setErrorMessage(null);
|
if (!v) setErrorMessage(null);
|
||||||
};
|
};
|
||||||
@@ -252,7 +267,9 @@ export function NoteDialog({
|
|||||||
}
|
}
|
||||||
|
|
||||||
startTransition(async () => {
|
startTransition(async () => {
|
||||||
let result: { success: boolean; message?: string; error?: string };
|
let result:
|
||||||
|
| Awaited<ReturnType<typeof createNoteAction>>
|
||||||
|
| Awaited<ReturnType<typeof updateNoteAction>>;
|
||||||
if (mode === "create") {
|
if (mode === "create") {
|
||||||
result = await createNoteAction(payload);
|
result = await createNoteAction(payload);
|
||||||
} else {
|
} else {
|
||||||
@@ -266,7 +283,31 @@ export function NoteDialog({
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
|
if (mode === "create" && pendingFiles.length > 0) {
|
||||||
|
const noteId = "data" in result ? result.data?.noteId : undefined;
|
||||||
|
if (noteId) {
|
||||||
|
let failedUploads = 0;
|
||||||
|
for (const file of pendingFiles) {
|
||||||
|
const upload = await uploadNoteAttachment(noteId, file);
|
||||||
|
if (!upload.success) failedUploads += 1;
|
||||||
|
}
|
||||||
|
if (failedUploads > 0) {
|
||||||
|
toast.warning(
|
||||||
|
failedUploads === 1
|
||||||
|
? "A nota foi salva, mas um anexo não pôde ser enviado."
|
||||||
|
: `A nota foi salva, mas ${failedUploads} anexos não puderam ser enviados.`,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
toast.success(
|
||||||
|
pendingFiles.length === 1
|
||||||
|
? "Anotação e anexo salvos."
|
||||||
|
: "Anotação e anexos salvos.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
toast.success(result.message);
|
toast.success(result.message);
|
||||||
|
}
|
||||||
setDialogOpen(false);
|
setDialogOpen(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -355,6 +396,7 @@ export function NoteDialog({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{isNote && (
|
{isNote && (
|
||||||
|
<div className="space-y-3">
|
||||||
<div className="space-y-1">
|
<div className="space-y-1">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<Label htmlFor="note-description">Conteúdo</Label>
|
<Label htmlFor="note-description">Conteúdo</Label>
|
||||||
@@ -385,6 +427,18 @@ export function NoteDialog({
|
|||||||
Ctrl+Enter para salvar
|
Ctrl+Enter para salvar
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<NoteAttachmentsField
|
||||||
|
noteId={mode === "update" ? note?.id : undefined}
|
||||||
|
attachments={noteAttachments}
|
||||||
|
pendingFiles={pendingFiles}
|
||||||
|
onAttachmentsChange={setNoteAttachments}
|
||||||
|
onPendingFilesChange={setPendingFiles}
|
||||||
|
onBusyChange={setIsAttachmentPending}
|
||||||
|
maxSizeMb={attachmentMaxSizeMb}
|
||||||
|
disabled={isPending}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{!isNote && (
|
{!isNote && (
|
||||||
@@ -517,7 +571,7 @@ export function NoteDialog({
|
|||||||
type="button"
|
type="button"
|
||||||
variant="outline"
|
variant="outline"
|
||||||
onClick={() => handleOpenChange(false)}
|
onClick={() => handleOpenChange(false)}
|
||||||
disabled={isPending}
|
disabled={isPending || isAttachmentPending}
|
||||||
>
|
>
|
||||||
Cancelar
|
Cancelar
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -22,9 +22,14 @@ import type { Note } from "./types";
|
|||||||
interface NotesPageProps {
|
interface NotesPageProps {
|
||||||
notes: Note[];
|
notes: Note[];
|
||||||
archivedNotes: Note[];
|
archivedNotes: Note[];
|
||||||
|
attachmentMaxSizeMb?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function NotesPage({ notes, archivedNotes }: NotesPageProps) {
|
export function NotesPage({
|
||||||
|
notes,
|
||||||
|
archivedNotes,
|
||||||
|
attachmentMaxSizeMb,
|
||||||
|
}: NotesPageProps) {
|
||||||
const [activeTab, setActiveTab] = useState("ativas");
|
const [activeTab, setActiveTab] = useState("ativas");
|
||||||
const [createOpen, setCreateOpen] = useState(false);
|
const [createOpen, setCreateOpen] = useState(false);
|
||||||
const [editOpen, setEditOpen] = useState(false);
|
const [editOpen, setEditOpen] = useState(false);
|
||||||
@@ -192,6 +197,7 @@ export function NotesPage({ notes, archivedNotes }: NotesPageProps) {
|
|||||||
mode="create"
|
mode="create"
|
||||||
open={createOpen}
|
open={createOpen}
|
||||||
onOpenChange={handleCreateOpenChange}
|
onOpenChange={handleCreateOpenChange}
|
||||||
|
attachmentMaxSizeMb={attachmentMaxSizeMb}
|
||||||
trigger={
|
trigger={
|
||||||
<Button className="w-full sm:w-auto">
|
<Button className="w-full sm:w-auto">
|
||||||
<RiAddFill className="size-4" />
|
<RiAddFill className="size-4" />
|
||||||
@@ -222,6 +228,7 @@ export function NotesPage({ notes, archivedNotes }: NotesPageProps) {
|
|||||||
note={noteToEdit ?? undefined}
|
note={noteToEdit ?? undefined}
|
||||||
open={editOpen}
|
open={editOpen}
|
||||||
onOpenChange={handleEditOpenChange}
|
onOpenChange={handleEditOpenChange}
|
||||||
|
attachmentMaxSizeMb={attachmentMaxSizeMb}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<NoteDetailsDialog
|
<NoteDetailsDialog
|
||||||
|
|||||||
@@ -14,6 +14,14 @@ export interface Note {
|
|||||||
tasks?: Task[];
|
tasks?: Task[];
|
||||||
archived: boolean;
|
archived: boolean;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
|
attachments: NoteAttachment[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface NoteAttachment {
|
||||||
|
attachmentId: string;
|
||||||
|
fileName: string;
|
||||||
|
fileSize: number;
|
||||||
|
mimeType: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface NoteFormValues {
|
export interface NoteFormValues {
|
||||||
|
|||||||
@@ -1,7 +1,14 @@
|
|||||||
import { and, eq } from "drizzle-orm";
|
import { and, desc, eq } from "drizzle-orm";
|
||||||
import { type Note, notes } from "@/db/schema";
|
import { attachments, type Note, noteAttachments, notes } from "@/db/schema";
|
||||||
import { db } from "@/shared/lib/db";
|
import { db } from "@/shared/lib/db";
|
||||||
|
|
||||||
|
export type NoteAttachmentData = {
|
||||||
|
attachmentId: string;
|
||||||
|
fileName: string;
|
||||||
|
fileSize: number;
|
||||||
|
mimeType: string;
|
||||||
|
};
|
||||||
|
|
||||||
type Task = {
|
type Task = {
|
||||||
id: string;
|
id: string;
|
||||||
text: string;
|
text: string;
|
||||||
@@ -16,6 +23,7 @@ type NoteData = {
|
|||||||
tasks?: Task[];
|
tasks?: Task[];
|
||||||
archived: boolean;
|
archived: boolean;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
|
attachments: NoteAttachmentData[];
|
||||||
};
|
};
|
||||||
|
|
||||||
function parseTasks(value: string | null): Task[] | undefined {
|
function parseTasks(value: string | null): Task[] | undefined {
|
||||||
@@ -31,7 +39,10 @@ function parseTasks(value: string | null): Task[] | undefined {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function toNoteData(note: Note): NoteData {
|
function toNoteData(
|
||||||
|
note: Note,
|
||||||
|
linkedAttachments: NoteAttachmentData[],
|
||||||
|
): NoteData {
|
||||||
return {
|
return {
|
||||||
id: note.id,
|
id: note.id,
|
||||||
title: (note.title ?? "").trim(),
|
title: (note.title ?? "").trim(),
|
||||||
@@ -40,34 +51,53 @@ function toNoteData(note: Note): NoteData {
|
|||||||
tasks: parseTasks(note.tasks),
|
tasks: parseTasks(note.tasks),
|
||||||
archived: note.archived,
|
archived: note.archived,
|
||||||
createdAt: note.createdAt.toISOString(),
|
createdAt: note.createdAt.toISOString(),
|
||||||
|
attachments: linkedAttachments,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async function fetchNotesForUser(userId: string): Promise<NoteData[]> {
|
|
||||||
const noteRows = await db.query.notes.findMany({
|
|
||||||
where: and(eq(notes.userId, userId), eq(notes.archived, false)),
|
|
||||||
orderBy: (table, { desc }) => [desc(table.createdAt)],
|
|
||||||
});
|
|
||||||
|
|
||||||
return noteRows.map(toNoteData);
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function fetchAllNotesForUser(
|
export async function fetchAllNotesForUser(
|
||||||
userId: string,
|
userId: string,
|
||||||
): Promise<{ activeNotes: NoteData[]; archivedNotes: NoteData[] }> {
|
): Promise<{ activeNotes: NoteData[]; archivedNotes: NoteData[] }> {
|
||||||
const [activeNotes, archivedNotes] = await Promise.all([
|
const [noteRows, attachmentRows] = await Promise.all([
|
||||||
fetchNotesForUser(userId),
|
db.query.notes.findMany({
|
||||||
fetchArchivedForUser(userId),
|
where: eq(notes.userId, userId),
|
||||||
|
orderBy: (table, { desc }) => [desc(table.createdAt)],
|
||||||
|
}),
|
||||||
|
db
|
||||||
|
.select({
|
||||||
|
noteId: noteAttachments.noteId,
|
||||||
|
attachmentId: attachments.id,
|
||||||
|
fileName: attachments.fileName,
|
||||||
|
fileSize: attachments.fileSize,
|
||||||
|
mimeType: attachments.mimeType,
|
||||||
|
})
|
||||||
|
.from(noteAttachments)
|
||||||
|
.innerJoin(
|
||||||
|
notes,
|
||||||
|
and(eq(noteAttachments.noteId, notes.id), eq(notes.userId, userId)),
|
||||||
|
)
|
||||||
|
.innerJoin(
|
||||||
|
attachments,
|
||||||
|
and(
|
||||||
|
eq(noteAttachments.attachmentId, attachments.id),
|
||||||
|
eq(attachments.userId, userId),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.orderBy(desc(attachments.createdAt)),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return { activeNotes, archivedNotes };
|
const attachmentsByNote = new Map<string, NoteAttachmentData[]>();
|
||||||
|
for (const { noteId, ...attachment } of attachmentRows) {
|
||||||
|
const current = attachmentsByNote.get(noteId) ?? [];
|
||||||
|
current.push(attachment);
|
||||||
|
attachmentsByNote.set(noteId, current);
|
||||||
}
|
}
|
||||||
|
const mapped = noteRows.map((note) =>
|
||||||
|
toNoteData(note, attachmentsByNote.get(note.id) ?? []),
|
||||||
|
);
|
||||||
|
|
||||||
async function fetchArchivedForUser(userId: string): Promise<NoteData[]> {
|
return {
|
||||||
const noteRows = await db.query.notes.findMany({
|
activeNotes: mapped.filter((note) => !note.archived),
|
||||||
where: and(eq(notes.userId, userId), eq(notes.archived, true)),
|
archivedNotes: mapped.filter((note) => note.archived),
|
||||||
orderBy: (table, { desc }) => [desc(table.createdAt)],
|
};
|
||||||
});
|
|
||||||
|
|
||||||
return noteRows.map(toNoteData);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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">
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
export type SectionType = "Adicionado" | "Alterado" | "Corrigido" | "Removido";
|
export type SectionType = "Adicionado" | "Alterado" | "Corrigido" | "Removido";
|
||||||
|
|
||||||
export const SECTION_TYPES: readonly SectionType[] = [
|
const SECTION_TYPES: readonly SectionType[] = [
|
||||||
"Adicionado",
|
"Adicionado",
|
||||||
"Alterado",
|
"Alterado",
|
||||||
"Corrigido",
|
"Corrigido",
|
||||||
|
|||||||
@@ -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))
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ export {
|
|||||||
} from "./actions/bulk-actions";
|
} from "./actions/bulk-actions";
|
||||||
export { exportTransactionsDataAction } from "./actions/export-actions";
|
export { exportTransactionsDataAction } from "./actions/export-actions";
|
||||||
export {
|
export {
|
||||||
|
convertTransactionToInstallmentAction,
|
||||||
|
convertTransactionToRecurringAction,
|
||||||
createTransactionAction,
|
createTransactionAction,
|
||||||
deleteTransactionAction,
|
deleteTransactionAction,
|
||||||
toggleTransactionSettlementAction,
|
toggleTransactionSettlementAction,
|
||||||
|
|||||||