Compare commits
38 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 | ||
|
|
78e778311d | ||
|
|
78c3ed5995 | ||
|
|
c34adba587 | ||
|
|
99bc049cf4 | ||
|
|
35abe1b0bf | ||
|
|
402f0072af | ||
|
|
02ee5bb758 | ||
|
|
41eecc2538 | ||
|
|
cdcc677787 |
@@ -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
|
||||||
|
|||||||
49
.github/workflows/ci.yml
vendored
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
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: 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/
|
||||||
|
|||||||
366
AGENTS.md
Normal file
@@ -0,0 +1,366 @@
|
|||||||
|
# AGENTS.md - OpenMonetis
|
||||||
|
|
||||||
|
> Self-hosted personal finance app (Next.js 16, React 19, PostgreSQL, Drizzle ORM, Better Auth, Tailwind 4, shadcn/ui).
|
||||||
|
> Portuguese UI, English folders/imports. Linter: Biome 2.x. Package manager: pnpm.
|
||||||
|
|
||||||
|
## Related Projects
|
||||||
|
|
||||||
|
- **OpenMonetis Companion** (`~/github/openmonetis-companion`): Android app que captura notificacoes de apps bancarios e envia para o OpenMonetis via API. Os itens chegam na feature `inbox` para revisao.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Critical Rules
|
||||||
|
|
||||||
|
1. **Sempre filtrar por `userId`** em queries.
|
||||||
|
2. **Usar `getAdminPayerId(userId)`** de `src/shared/lib/payers/get-admin-id.ts` ao inves de JOIN com `payers` para descobrir o admin.
|
||||||
|
3. **Periods** usam formato `YYYY-MM` (ex: `"2025-11"`). Utils em `src/shared/utils/period/`.
|
||||||
|
4. **Moeda**: R$ com 2 decimais. DB: `numeric(12, 2)`. Utils em `src/shared/utils/currency.ts`.
|
||||||
|
5. **Revalidation**: usar `revalidateForEntity("entity")` de `src/shared/lib/actions/helpers.ts` apos mutations.
|
||||||
|
6. **Versionamento 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.
|
||||||
|
8. **Commit messages**: agrupar por natureza. em pt-br. seguindo o padrao do sistema.
|
||||||
|
9. **README.md**: sempre que fizer alteracoes significativas, atualize o README.md.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
### Feature-First
|
||||||
|
|
||||||
|
- `src/app/`: roteamento, layouts, loading states e paginas finas
|
||||||
|
- `src/features/`: codigo de dominio por feature
|
||||||
|
- `src/shared/`: tudo que e genuinamente reutilizado entre features
|
||||||
|
- `src/db/`: schema do banco
|
||||||
|
|
||||||
|
### Regra Feature vs Shared
|
||||||
|
|
||||||
|
Use esta pergunta:
|
||||||
|
|
||||||
|
> Se eu deletar esta feature, este arquivo deveria sumir junto?
|
||||||
|
|
||||||
|
- Sim: vai para `src/features/<feature>/`
|
||||||
|
- Nao: vai para `src/shared/`
|
||||||
|
|
||||||
|
### Features nao importam outras features
|
||||||
|
|
||||||
|
Se um contrato cruza dominios, ele deve morar em `src/shared/`.
|
||||||
|
|
||||||
|
**Excecao intencional: `attachments` depende de `transactions`**
|
||||||
|
|
||||||
|
`src/features/attachments` importa `TransactionDialog`, `TransactionDetailsDialog` e `TransactionItem` diretamente de `src/features/transactions`. Isso e uma dependencia explicita e aceita: anexos sao semanticamente uma extensao de lancamentos — existem por causa deles e nao fazem sentido sem esse contexto. Mover esses componentes para `shared/` seria errado (eles pertencem a transactions). Nao tratar isso como bug a corrigir.
|
||||||
|
|
||||||
|
Exemplos comuns:
|
||||||
|
|
||||||
|
- auth: `src/shared/lib/auth/*`
|
||||||
|
- db: `src/shared/lib/db.ts`
|
||||||
|
- revalidation helpers: `src/shared/lib/actions/*`
|
||||||
|
- payers cross-domain helpers: `src/shared/lib/payers/*`
|
||||||
|
- period/currency/date: `src/shared/utils/*`
|
||||||
|
- shadcn/ui: `src/shared/components/ui/*`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Directory Structure
|
||||||
|
|
||||||
|
```text
|
||||||
|
src/
|
||||||
|
├── app/
|
||||||
|
│ ├── (auth)/
|
||||||
|
│ │ ├── login/page.tsx
|
||||||
|
│ │ └── signup/page.tsx
|
||||||
|
│ ├── (dashboard)/
|
||||||
|
│ │ ├── dashboard/
|
||||||
|
│ │ ├── transactions/
|
||||||
|
│ │ ├── cards/
|
||||||
|
│ │ │ └── [cardId]/invoice/
|
||||||
|
│ │ ├── accounts/
|
||||||
|
│ │ │ └── [accountId]/statement/
|
||||||
|
│ │ ├── categories/
|
||||||
|
│ │ │ ├── [categoryId]/
|
||||||
|
│ │ │ └── history/
|
||||||
|
│ │ ├── budgets/
|
||||||
|
│ │ ├── payers/
|
||||||
|
│ │ │ └── [payerId]/
|
||||||
|
│ │ ├── notes/
|
||||||
|
│ │ ├── insights/
|
||||||
|
│ │ ├── calendar/
|
||||||
|
│ │ ├── inbox/
|
||||||
|
│ │ ├── attachments/
|
||||||
|
│ │ ├── changelog/
|
||||||
|
│ │ ├── reports/
|
||||||
|
│ │ │ ├── category-trends/
|
||||||
|
│ │ │ ├── card-usage/
|
||||||
|
│ │ │ ├── installment-analysis/
|
||||||
|
│ │ │ └── establishments/
|
||||||
|
│ │ └── settings/
|
||||||
|
│ ├── (landing-page)/
|
||||||
|
│ ├── api/
|
||||||
|
│ ├── globals.css
|
||||||
|
│ └── layout.tsx
|
||||||
|
├── features/ # cada feature segue: actions.ts, queries.ts, actions/, components/, hooks/, lib/
|
||||||
|
│ ├── auth/
|
||||||
|
│ ├── landing/
|
||||||
|
│ ├── dashboard/
|
||||||
|
│ ├── transactions/
|
||||||
|
│ ├── cards/
|
||||||
|
│ ├── invoices/
|
||||||
|
│ ├── accounts/
|
||||||
|
│ ├── categories/
|
||||||
|
│ ├── budgets/
|
||||||
|
│ ├── payers/
|
||||||
|
│ ├── notes/
|
||||||
|
│ ├── insights/
|
||||||
|
│ ├── calendar/
|
||||||
|
│ ├── inbox/
|
||||||
|
│ ├── attachments/
|
||||||
|
│ ├── reports/
|
||||||
|
│ └── settings/
|
||||||
|
├── shared/
|
||||||
|
│ ├── components/
|
||||||
|
│ │ ├── ui/ # shadcn/ui primitives
|
||||||
|
│ │ ├── navigation/ # navbar, sidebar, breadcrumbs
|
||||||
|
│ │ ├── providers/ # React context providers
|
||||||
|
│ │ ├── brand/ # logos do app (logo, logo-icon, logo-text)
|
||||||
|
│ │ ├── widgets/ # widget-card, widget-empty-state, expandable-widget-card
|
||||||
|
│ │ ├── feedback/ # empty-state, status-dot, payment-success
|
||||||
|
│ │ ├── month-picker/
|
||||||
|
│ │ ├── logo-picker/
|
||||||
|
│ │ ├── calculator/
|
||||||
|
│ │ ├── entity-avatar/
|
||||||
|
│ │ └── skeletons/
|
||||||
|
│ ├── hooks/
|
||||||
|
│ ├── lib/
|
||||||
|
│ │ ├── actions/
|
||||||
|
│ │ ├── auth/
|
||||||
|
│ │ ├── accounts/
|
||||||
|
│ │ ├── cards/
|
||||||
|
│ │ ├── calculator/
|
||||||
|
│ │ ├── categories/
|
||||||
|
│ │ ├── email/
|
||||||
|
│ │ ├── import/
|
||||||
|
│ │ ├── installments/
|
||||||
|
│ │ ├── invoices/
|
||||||
|
│ │ ├── logo/
|
||||||
|
│ │ ├── notifications/
|
||||||
|
│ │ ├── payers/
|
||||||
|
│ │ ├── schemas/
|
||||||
|
│ │ ├── storage/
|
||||||
|
│ │ ├── transfers/
|
||||||
|
│ │ ├── types/
|
||||||
|
│ │ ├── version/
|
||||||
|
│ │ └── db.ts
|
||||||
|
│ └── utils/
|
||||||
|
│ ├── period/
|
||||||
|
│ ├── calculator.ts
|
||||||
|
│ ├── calendar.ts
|
||||||
|
│ ├── category-colors.ts
|
||||||
|
│ ├── currency.ts
|
||||||
|
│ ├── date.ts
|
||||||
|
│ ├── export-branding.ts
|
||||||
|
│ ├── fetch-json.ts
|
||||||
|
│ ├── financial-dates.ts
|
||||||
|
│ ├── icons.tsx
|
||||||
|
│ ├── id.ts
|
||||||
|
│ ├── initials.ts
|
||||||
|
│ ├── math.ts
|
||||||
|
│ ├── number.ts
|
||||||
|
│ ├── percentage.ts
|
||||||
|
│ ├── string.ts
|
||||||
|
│ └── ui.ts
|
||||||
|
└── db/
|
||||||
|
└── schema.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
### Estrutura interna padrão de uma feature
|
||||||
|
|
||||||
|
Toda feature em `src/features/<nome>/` segue:
|
||||||
|
|
||||||
|
```text
|
||||||
|
<feature>/
|
||||||
|
├── actions.ts # entry point de Server Actions (barrel quando há actions/)
|
||||||
|
├── queries.ts # entry point de leitura do banco
|
||||||
|
├── actions/ # (opcional) Server Actions divididas por domínio quando o volume cresce
|
||||||
|
├── components/ # componentes de UI da feature
|
||||||
|
├── hooks/ # React hooks específicos da feature
|
||||||
|
└── lib/ # helpers, types, sub-queries e constantes internas
|
||||||
|
```
|
||||||
|
|
||||||
|
`actions.ts` e `queries.ts` são as portas de entrada da feature. Tudo que é helper interno fica em `lib/`. Componentes e hooks ficam nas pastas com nome óbvio.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Import Patterns
|
||||||
|
|
||||||
|
### Preferidos
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { getUser } from "@/shared/lib/auth/server";
|
||||||
|
import { revalidateForEntity } from "@/shared/lib/actions/helpers";
|
||||||
|
import { parsePeriodParam } from "@/shared/utils/period";
|
||||||
|
import { TransactionsPage } from "@/features/transactions/components/page/transactions-page";
|
||||||
|
import { fetchLancamentos } from "@/features/transactions/queries";
|
||||||
|
```
|
||||||
|
|
||||||
|
### Evitar
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { Something } from "@/components/...";
|
||||||
|
import { Something } from "@/lib/...";
|
||||||
|
import { something } from "@/app/(dashboard)/...";
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## App Router Pattern
|
||||||
|
|
||||||
|
Paginas em `src/app/` devem ser finas:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { getUser } from "@/shared/lib/auth/server";
|
||||||
|
import { TransactionsPage } from "@/features/transactions/components/page/transactions-page";
|
||||||
|
import { fetchLancamentos } from "@/features/transactions/queries";
|
||||||
|
|
||||||
|
export default async function Page() {
|
||||||
|
const user = await getUser();
|
||||||
|
const data = await fetchLancamentos([/* filters */]);
|
||||||
|
return <TransactionsPage {...data} />;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Layouts, `loading.tsx` e metadata continuam em `src/app/`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Naming
|
||||||
|
|
||||||
|
### Routes / folders
|
||||||
|
|
||||||
|
| Portugues | English |
|
||||||
|
|---|---|
|
||||||
|
| `lancamentos` | `transactions` |
|
||||||
|
| `cartoes` | `cards` |
|
||||||
|
| `contas` | `accounts` |
|
||||||
|
| `categorias` | `categories` |
|
||||||
|
| `orcamentos` | `budgets` |
|
||||||
|
| `pessoas` | `payers` |
|
||||||
|
|
||||||
|
> **Nota:** o conceito de "pagador" foi renomeado para **"pessoa"** na UI (labels, toasts, textos visíveis ao usuário). O código, rotas e schema continuam usando o termo original em inglês (`payer`, `payerId`, `adminPayerId`) e em português interno (`pagador` como variável). Não renomear esses identificadores — a divergência entre UI e código é intencional e documentada.
|
||||||
|
| `anotacoes` | `notes` |
|
||||||
|
| `calendario` | `calendar` |
|
||||||
|
| `ajustes` | `settings` |
|
||||||
|
| `pre-lancamentos` | `inbox` |
|
||||||
|
| `relatorios/tendencias` | `reports/category-trends` |
|
||||||
|
| `relatorios/uso-cartoes` | `reports/card-usage` |
|
||||||
|
| `relatorios/analise-parcelas` | `reports/installment-analysis` |
|
||||||
|
| `relatorios/estabelecimentos` | `reports/establishments` |
|
||||||
|
| `contas/[contaId]/extrato` | `accounts/[accountId]/statement` |
|
||||||
|
| `cartoes/[cartaoId]/fatura` | `cards/[cardId]/invoice` |
|
||||||
|
| `categorias/historico` | `categories/history` |
|
||||||
|
| `changelog` | `settings/changelog` |
|
||||||
|
|
||||||
|
### Files
|
||||||
|
|
||||||
|
- preferir `kebab-case`
|
||||||
|
- preferir nomes em ingles
|
||||||
|
- manter nomes internos de tipos/funcoes somente quando a troca aumentar risco sem ganho real
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pnpm run dev
|
||||||
|
pnpm run build
|
||||||
|
pnpm run lint
|
||||||
|
pnpm run lint:fix
|
||||||
|
pnpm exec next typegen
|
||||||
|
pnpm exec tsc --noEmit
|
||||||
|
pnpm run db:generate
|
||||||
|
pnpm run db:push
|
||||||
|
pnpm run db:studio
|
||||||
|
pnpm run docker:up:db
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Revalidation
|
||||||
|
|
||||||
|
Arquivo: `src/shared/lib/actions/helpers.ts`
|
||||||
|
|
||||||
|
- atualizar sempre os paths em ingles
|
||||||
|
- lembrar de manter a tag `"dashboard"` para invalidacoes financeiras
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Auth
|
||||||
|
|
||||||
|
- `getUser()` / `getUserId()` em `src/shared/lib/auth/server.ts`
|
||||||
|
- sessao deduplicada por request com `React.cache()`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Dashboard Fetcher
|
||||||
|
|
||||||
|
Padrao recomendado:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { getAdminPayerId } from "@/shared/lib/payers/get-admin-id";
|
||||||
|
|
||||||
|
export async function fetchData(userId: string, period: string) {
|
||||||
|
const adminPayerId = await getAdminPayerId(userId);
|
||||||
|
if (!adminPayerId) return [];
|
||||||
|
|
||||||
|
return db.query.transactions.findMany({
|
||||||
|
where: /* sempre com userId + adminPayerId + period */,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## New Feature Checklist
|
||||||
|
|
||||||
|
1. Criar a rota fina em `src/app/(dashboard)/<feature>/page.tsx`
|
||||||
|
2. Criar a feature em `src/features/<feature>/`
|
||||||
|
3. Separar:
|
||||||
|
- `components/`
|
||||||
|
- `queries.ts` (entry point de leitura)
|
||||||
|
- `actions.ts` (entry point de Server Actions; vira barrel quando crescer e migrar para `actions/`)
|
||||||
|
- `lib/` para helpers internos, sub-queries por tópico, types e constantes da feature
|
||||||
|
- `types.ts` ou `schemas.ts` quando fizer sentido (alternativa a `lib/`)
|
||||||
|
- `hooks/` quando houver hooks específicos da feature
|
||||||
|
4. Extrair para `src/shared/` tudo que for reutilizavel
|
||||||
|
5. Atualizar navegacao e `revalidateForEntity()` se a feature tiver CRUD
|
||||||
|
6. Rodar:
|
||||||
|
- `pnpm exec next typegen`
|
||||||
|
- `pnpm exec tsc --noEmit`
|
||||||
|
- `pnpm run lint`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Security Rules
|
||||||
|
|
||||||
|
Regras aplicadas automaticamente ao gerar codigo.
|
||||||
|
|
||||||
|
### Secrets
|
||||||
|
Nunca colocar API keys, credenciais de banco ou tokens em codigo frontend. Evitar variaveis prefixadas com `NEXT_PUBLIC_` para dados sensiveis — estas sao bundladas no cliente. Usar variaveis server-side apenas. `.env` deve estar no `.gitignore` antes do primeiro commit. `.env.example` deve ter apenas placeholders.
|
||||||
|
|
||||||
|
### Autenticacao & Autorizacao
|
||||||
|
Toda rota protegida em `src/app/api/` requer `getUser()` ou `getOptionalUserSession()` antes de qualquer logica, retornando 401 para nao autenticados. Rotas com IDs de recursos devem verificar ownership: `eq(table.userId, userId)`. Rotas admin devem checar role e retornar 403 para nao-admins. Session cookies em Better Auth ja tem `httpOnly`, `secure` e `sameSite` configurados — nao alterar.
|
||||||
|
|
||||||
|
### Input & Output
|
||||||
|
Usar Drizzle ORM (parametrizado por padrao) — nunca concatenar input de usuario em SQL. Validar todo input com Zod antes de usar. Upload de arquivos: usar whitelist de MIME types (`ALLOWED_MIME_TYPES`), presigned URLs para S3, token de upload assinado com verificacao pos-upload. Nunca usar `dangerouslySetInnerHTML` com conteudo de usuario.
|
||||||
|
|
||||||
|
### Headers & CSP
|
||||||
|
CSP definida em `src/proxy.ts` via middleware — alterar la, nao em `next.config.ts`. Headers de seguranca (HSTS, X-Frame-Options, etc.) definidos em `next.config.ts`. Nao remover nem enfraquecer essas configuracoes.
|
||||||
|
|
||||||
|
### Rate Limiting
|
||||||
|
Login: 5 tentativas/min. Signup: 3 tentativas/min. API tokens: 100 req/min (inbox), 20 req/min (batch). Configurado em `src/shared/lib/auth/config.ts` e nas rotas de inbox. Nao remover.
|
||||||
|
|
||||||
|
### Tratamento de Erros
|
||||||
|
Erros nao devem expor stack traces, paths ou nomes de bibliotecas ao cliente. Usar mensagens genericas: `"Algo deu errado"`. Logar detalhes apenas no servidor com `console.error()`.
|
||||||
|
|
||||||
|
### Dependencias
|
||||||
|
Verificar pacotes novos sugeridos pela IA em npmjs.com antes de instalar. Red flags: menos de 1.000 downloads/semana, publicado nos ultimos 30 dias, nome muito parecido com pacote popular. Rodar `pnpm audit` periodicamente.
|
||||||
|
|
||||||
|
---
|
||||||
139
CHANGELOG.md
@@ -5,6 +5,145 @@ 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.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
|
||||||
|
|
||||||
|
Esta versão atualiza as imagens de apresentação do OpenMonetis na landing page e no compartilhamento em redes sociais.
|
||||||
|
|
||||||
|
### Alterado
|
||||||
|
- Landing page: atualizadas as imagens de preview do dashboard e da versão PWA.
|
||||||
|
- Compartilhamento: ajustada a imagem usada nos metadados sociais da landing page.
|
||||||
|
|
||||||
|
## [2.7.1] - 2026-05-30
|
||||||
|
|
||||||
|
Esta versão melhora a clareza dos fluxos de lançamento e a experiência do dashboard. Boletos de receita agora diferenciam pagamentos de recebimentos, a navegação mensal ficou mais direta e o painel ganhou atalhos mais úteis com personalização simplificada.
|
||||||
|
|
||||||
|
### Adicionado
|
||||||
|
- Preferências: nova opção para exibir ou ocultar o card `Resumo da operação` no modal de lançamento.
|
||||||
|
- Navegação mensal: ao passar o mouse, focar ou clicar no período selecionado, agora é possível abrir um seletor e ir diretamente para outro mês.
|
||||||
|
|
||||||
|
### Alterado
|
||||||
|
- Documentação: o guia visual foi reescrito com os tokens, temas, componentes e práticas de acessibilidade atuais; o README agora apresenta a identidade visual e as preferências disponíveis.
|
||||||
|
- Dashboard: os cards de receitas e despesas agora oferecem um atalho discreto para abrir os lançamentos da pessoa principal filtrados pelo tipo e período.
|
||||||
|
- Dashboard: a configuração e a reordenação de widgets agora partem de uma única ação `Personalizar`, com controle de visibilidade durante a edição.
|
||||||
|
- Dashboard: em telas pequenas, os atalhos para receita, despesa e anotação foram agrupados no menu `Adicionar`.
|
||||||
|
- Dashboard: os títulos dos widgets agora usam sentence case para reduzir ruído visual.
|
||||||
|
- Dashboard: os widgets receberam uma revisão ampla de UX, com hierarquia visual mais clara, listas compactas, textos mais diretos, estados acessíveis e navegação interna consistente.
|
||||||
|
- Dashboard: o widget `Comportamento de pagamento` foi renomeado para `Distribuição de despesas`.
|
||||||
|
- Dashboard: limites de orçamento agora aparecem apenas no widget de despesas por categoria.
|
||||||
|
- Dashboard: o widget `Panorama de gastos` agora exibe todos os lançamentos sem filtro adicional por cartão.
|
||||||
|
- Navegação: o menu de finanças agora oferece submenus para abrir diretamente as faturas dos cartões e os extratos das contas ativas.
|
||||||
|
- Lançamentos: ao passar o mouse sobre `Filtros`, os filtros ativos agora aparecem em um painel compacto com remoção individual e ação para limpar todos de uma vez.
|
||||||
|
|
||||||
|
### Corrigido
|
||||||
|
- Dashboard: o saldo consolidado do widget `Minhas contas` não inclui mais contas inativas.
|
||||||
|
- Boletos: lançamentos de receita agora exibem ações e status como `Receber`, `Recebido` e `Recebido em`, enquanto despesas continuam usando `Pagar`, `Pago` e `Pago em`.
|
||||||
|
- Dashboard: o modal de baixa de boleto agora usa textos de recebimento e conta de destino para receitas.
|
||||||
|
- Calendário e pessoas: os detalhes de boletos de receita agora preservam a nomenclatura de recebimento.
|
||||||
|
|
||||||
## [2.7.0] - 2026-05-28
|
## [2.7.0] - 2026-05-28
|
||||||
|
|
||||||
Esta versão amplia o OpenMonetis para quem usa o app todos os dias e para quem prefere mais controle sobre os próprios dados. Os Insights ganham novas opções de IA, incluindo modelos locais via Ollama, enquanto a autenticação fica mais confortável em dispositivos pessoais. Também entram melhorias práticas em contas, lançamentos compartilhados, filtros, relatórios e dashboard, deixando os fluxos financeiros mais completos e fáceis de revisar.
|
Esta versão amplia o OpenMonetis para quem usa o app todos os dias e para quem prefere mais controle sobre os próprios dados. Os Insights ganham novas opções de IA, incluindo modelos locais via Ollama, enquanto a autenticação fica mais confortável em dispositivos pessoais. Também entram melhorias práticas em contas, lançamentos compartilhados, filtros, relatórios e dashboard, deixando os fluxos financeiros mais completos e fáceis de revisar.
|
||||||
|
|||||||
@@ -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.
|
||||||
|
|||||||
479
DESIGN.md
@@ -1,389 +1,178 @@
|
|||||||
# Design System Inspired by OpenMonetis
|
# Design System do OpenMonetis
|
||||||
|
|
||||||
## 1. Visual Theme & Atmosphere
|
Este documento descreve a identidade visual implementada no OpenMonetis. Ele deve
|
||||||
|
ser usado como referência ao criar telas, revisar componentes e manter a
|
||||||
|
experiência consistente entre dashboard, relatórios, formulários e landing page.
|
||||||
|
|
||||||
OpenMonetis embodies a warm, approachable financial management aesthetic grounded in trust and transparency. The design system combines a rich warm-orange accent palette with a sophisticated warm-neutral foundation, creating an interface that feels both professional and inviting. The typography and spacing work together to emphasize clarity and hierarchy, supporting the open-source ethos of personal financial control. The visual atmosphere prioritizes legibility and calm navigation, with generous whitespace and deliberate color restraint—the bold orange is reserved for critical calls-to-action and highlights, while the warm grays and blacks anchor the interface with stability and focus.
|
## 1. Direção visual
|
||||||
|
|
||||||
**Key Characteristics**
|
O OpenMonetis busca tornar a gestão financeira clara e acolhedora. A interface
|
||||||
- Warm, approachable color story with a dominant orange accent (`#FF7733`)
|
usa superfícies quentes, poucos elementos decorativos e uma cor laranja de
|
||||||
- Generous whitespace and breathing room between sections
|
destaque para orientar o olhar sem transformar toda ação em urgência.
|
||||||
- High contrast between backgrounds and text for accessibility
|
|
||||||
- Clear typographic hierarchy using Inter for all text and UI
|
|
||||||
- Minimal elevation and shadow treatment—mostly flat design
|
|
||||||
- Subtle border accents in warm grays to define surfaces
|
|
||||||
- Open-source transparency reflected in straightforward, honest design language
|
|
||||||
|
|
||||||
## 2. Color Palette & Roles
|
Princípios:
|
||||||
|
|
||||||
### Primary
|
- priorizar legibilidade e hierarquia em telas com muitos dados;
|
||||||
- **Primary Accent** (`#FF7733`): Used for primary call-to-action buttons, highlights, and key interactive elements throughout the interface; draws user attention to the most important actions
|
- usar laranja para ações principais, seleção e foco;
|
||||||
- **Primary Dark** (`#443732`): Warm-brown anchor color used extensively for text, headings, and interactive elements; provides the primary text color across the system
|
- manter superfícies leves no tema claro e contraste confortável no tema escuro;
|
||||||
|
- aplicar cores semânticas para comunicar estado, não como decoração;
|
||||||
|
- preservar espaço suficiente entre blocos para evitar ruído visual;
|
||||||
|
- favorecer componentes responsivos e navegação acessível por teclado.
|
||||||
|
|
||||||
### Interactive
|
## 2. Fonte de verdade
|
||||||
- **Interactive Neutral** (`#0F0D0C`): Near-black used for primary text and strong emphasis elements; highest contrast state
|
|
||||||
- **Interactive Overlay** (`#0006`): Transparent black overlay at 24% opacity; used for hover states, modals, and depth layering
|
|
||||||
|
|
||||||
### Neutral Scale
|
Os tokens globais estão definidos em
|
||||||
- **Neutral 900** (`#2A2827`): Very dark warm gray; used for secondary text and disabled states
|
[`src/app/globals.css`](./src/app/globals.css). Componentes reutilizáveis ficam
|
||||||
- **Neutral 800** (`#322C2A`): Dark warm gray; alternative text color for lower-emphasis content
|
em [`src/shared/components/ui/`](./src/shared/components/ui/) e seguem o padrão
|
||||||
- **Neutral 700** (`#676260`): Medium warm gray; used for tertiary text, captions, and metadata
|
do shadcn/ui com Radix UI e Tailwind CSS 4.
|
||||||
- **Neutral 50** (`#FCF7F6`): Almost-white warm cream; primary background color for light surfaces
|
|
||||||
- **Neutral 100** (`#F8F6F4`): Very light warm gray; secondary background and subtle surface distinction
|
|
||||||
- **Neutral 200** (`#F5F2EF`): Light warm gray; tertiary background and card interiors
|
|
||||||
- **Neutral 300** (`#F0EEEC`): Pale warm gray; border and divider lines
|
|
||||||
|
|
||||||
### Surface & Borders
|
Ao implementar uma tela:
|
||||||
- **Surface** (`#FFFFFF`): Pure white; primary card and container background; high-contrast surface
|
|
||||||
- **Border Light** (`#F0EEEC`): Pale warm gray used for subtle borders between elements
|
|
||||||
- **Border Dark** (`#2A2827`): Dark warm gray; stronger borders for defined card boundaries
|
|
||||||
|
|
||||||
### Semantic / Status
|
1. use classes semânticas como `bg-background`, `bg-card`, `text-foreground`,
|
||||||
- **Success** (`#0E9D6E`): Green used for positive status indicators, confirmation states, and success messages
|
`text-muted-foreground`, `border-border` e `ring-ring`;
|
||||||
- **Warning** (`#F7A439`): Amber used for cautionary states, warnings, and attention-drawing alerts
|
2. reutilize os componentes em `src/shared/components/ui/`;
|
||||||
- **Error** (`#F53F2D`): Red-orange used for error states, destructive actions, and validation failures
|
3. evite cores hexadecimais e valores arbitrários quando já existir um token;
|
||||||
- **Error Alt** (`#D40C1A`): Deep red alternative for critical errors and danger states
|
4. valide os dois temas antes de concluir a alteração.
|
||||||
|
|
||||||
## 3. Typography Rules
|
## 3. Cores
|
||||||
|
|
||||||
### Font Family
|
A paleta é definida em OKLCH para manter uma percepção de contraste mais
|
||||||
**Primary:** Inter (sans-serif)
|
consistente. Não copie os valores para componentes: use os tokens semânticos.
|
||||||
Fallback: `Inter, system-ui, -apple-system, sans-serif`
|
|
||||||
|
|
||||||
**Monospace:** ui-monospace
|
| Token | Papel |
|
||||||
Fallback: `ui-monospace, 'Courier New', monospace`
|
|---|---|
|
||||||
|
| `background` | Fundo geral da aplicação |
|
||||||
|
| `foreground` | Texto principal |
|
||||||
|
| `card` / `card-foreground` | Cards e conteúdo em destaque |
|
||||||
|
| `popover` / `popover-foreground` | Menus, popovers e overlays |
|
||||||
|
| `primary` / `primary-foreground` | Ações principais, foco e seleção |
|
||||||
|
| `secondary` / `secondary-foreground` | Ações secundárias e superfícies discretas |
|
||||||
|
| `muted` / `muted-foreground` | Apoio visual, descrições e metadados |
|
||||||
|
| `accent` / `accent-foreground` | Hover e seleção leve |
|
||||||
|
| `success` | Confirmações, recebimentos e estados positivos |
|
||||||
|
| `warning` | Atenção, vencimentos e estados intermediários |
|
||||||
|
| `info` | Informações auxiliares |
|
||||||
|
| `destructive` | Erros e ações destrutivas |
|
||||||
|
| `border`, `input`, `ring` | Bordas, campos e foco |
|
||||||
|
|
||||||
### Hierarchy
|
### Gráficos
|
||||||
|
|
||||||
| Role | Font | Size | Weight | Line Height | Letter Spacing | Notes |
|
Gráficos usam `chart-1` a `chart-10`. Visualizações que precisam de uma escala
|
||||||
|------|------|------|--------|-------------|----------------|-------|
|
sequencial quente podem usar `data-1` a `data-6`. A cor nunca deve ser o único
|
||||||
| Display / H1 | Inter | 60px | 600 | 60px | 0px | Page titles and hero headlines; maximum visual impact |
|
meio de distinguir uma série: inclua legenda, rótulo ou tooltip.
|
||||||
| Heading H2 | Inter | 36px | 600 | 40px | 0px | Section headers and major subsections |
|
|
||||||
| Heading H3 | Inter | 16px | 600 | 20px | 0px | Card titles and smaller section headers |
|
|
||||||
| Body | Inter | 20px | 400 | 28px | 0px | Descriptive text, paragraphs, and long-form content |
|
|
||||||
| Body Secondary | Inter | 16px | 400 | 24px | 0px | Standard body text, list items, and descriptions |
|
|
||||||
| Emphasis / Span | Inter | 14px | 500 | 20px | 0px | Emphasized text, labels, and badge content |
|
|
||||||
| Button | Inter | 14px | 500 | 20px | 0px | All button text; medium weight for clarity |
|
|
||||||
| Caption | Inter | 14px | 400 | 20px | 0px | Metadata, timestamps, and small supporting text |
|
|
||||||
| Code | ui-monospace | 14px | 400 | 20px | 0px | Code blocks and technical content |
|
|
||||||
|
|
||||||
### Principles
|
### Tema escuro
|
||||||
- **Contrast & Clarity:** Text color `#0F0D0C` on light backgrounds; `#FFFFFF` on dark backgrounds
|
|
||||||
- **Weight Hierarchy:** Use 600 weight for all headings; 500 for interactive/emphasized text; 400 for body
|
|
||||||
- **Scale Progression:** Sizes increase in meaningful increments (14 → 16 → 20 → 36 → 60); maintain consistent rhythm
|
|
||||||
- **Line Height:** Body text uses 1.4× line height multiplier for comfortable reading; headings use tighter ratio (1:1) for impact
|
|
||||||
- **Readability First:** Avoid line lengths over 80 characters for long-form content; increase line height on smaller screens
|
|
||||||
|
|
||||||
## 4. Component Stylings
|
O tema escuro redefine a mesma camada semântica dentro de `.dark`. Não crie uma
|
||||||
|
segunda árvore de componentes para suportá-lo. Prefira tokens e, somente quando
|
||||||
|
necessário, variantes Tailwind `dark:`.
|
||||||
|
|
||||||
### Buttons
|
## 4. Tipografia
|
||||||
|
|
||||||
#### Primary Button
|
A família principal é **Bricolage Grotesque**, carregada com `next/font` em
|
||||||
- **Background:** `#FF7733`
|
[`public/fonts/font_index.ts`](./public/fonts/font_index.ts). Os pesos
|
||||||
- **Text Color:** `#FFFFFF`
|
disponíveis são `500`, `600` e `700`, com fallback para Arial e fontes sans-serif
|
||||||
- **Font Size:** `14px`
|
do sistema.
|
||||||
- **Font Weight:** `500`
|
|
||||||
- **Font Family:** `Inter`
|
|
||||||
- **Padding:** `8px 16px`
|
|
||||||
- **Border Radius:** `9.2px`
|
|
||||||
- **Border:** `0px solid transparent`
|
|
||||||
- **Height:** `40px`
|
|
||||||
- **Box Shadow:** `none`
|
|
||||||
- **Hover State:** Darken background to `#E55F1F`; add subtle shadow `0px 2px 8px rgba(0, 0, 0, 0.12)`
|
|
||||||
- **Active State:** Darken further to `#CC5118`; increase shadow
|
|
||||||
- **Disabled State:** Background `#E8E3E0`; text color `#999890`; cursor not-allowed
|
|
||||||
|
|
||||||
#### Secondary Button
|
Diretrizes:
|
||||||
- **Background:** `#FFFFFF`
|
|
||||||
- **Text Color:** `#2A2827`
|
|
||||||
- **Font Size:** `14px`
|
|
||||||
- **Font Weight:** `500`
|
|
||||||
- **Font Family:** `Inter`
|
|
||||||
- **Padding:** `8px 24px`
|
|
||||||
- **Border Radius:** `9.2px`
|
|
||||||
- **Border:** `1px solid #F0EEEC`
|
|
||||||
- **Height:** `40px`
|
|
||||||
- **Box Shadow:** `0px 1px 3px rgba(0, 0, 0, 0.06)`
|
|
||||||
- **Hover State:** Background `#F8F6F4`; border color `#E8E3E0`
|
|
||||||
- **Active State:** Background `#F0EEEC`; border color `#D5CCCA`
|
|
||||||
- **Disabled State:** Background `#FAFAF8`; text color `#BFBAB7`; border color `#F0EEEC`
|
|
||||||
|
|
||||||
#### Ghost Button
|
- corpo e controles: `text-sm` ou `text-base`;
|
||||||
- **Background:** `transparent`
|
- descrições e metadados: `text-sm text-muted-foreground`;
|
||||||
- **Text Color:** `#443732`
|
- títulos de card: `text-base font-medium`;
|
||||||
- **Font Size:** `14px`
|
- títulos de modal: `text-lg font-semibold`;
|
||||||
- **Font Weight:** `500`
|
- títulos de página: hierarquia responsiva conforme a densidade da tela;
|
||||||
- **Font Family:** `Inter`
|
- números financeiros: destaque por peso e alinhamento, sem depender apenas da
|
||||||
- **Padding:** `6px 8px`
|
cor.
|
||||||
- **Border Radius:** `9.2px`
|
|
||||||
- **Border:** `0px solid transparent`
|
|
||||||
- **Height:** `32px`
|
|
||||||
- **Box Shadow:** `none`
|
|
||||||
- **Hover State:** Background `rgba(68, 55, 50, 0.05)`
|
|
||||||
- **Active State:** Background `rgba(68, 55, 50, 0.1)`
|
|
||||||
- **Disabled State:** Text color `#BFBAB7`; cursor not-allowed
|
|
||||||
|
|
||||||
#### Icon Button
|
## 5. Espaçamento, raio e elevação
|
||||||
- **Background:** `transparent`
|
|
||||||
- **Icon Color:** `#443732`
|
|
||||||
- **Size:** `32px` × `32px`
|
|
||||||
- **Border Radius:** `9.2px`
|
|
||||||
- **Border:** `0px solid transparent`
|
|
||||||
- **Padding:** `0px`
|
|
||||||
- **Box Shadow:** `none`
|
|
||||||
- **Hover State:** Background `rgba(68, 55, 50, 0.08)`
|
|
||||||
- **Active State:** Background `rgba(68, 55, 50, 0.12)`
|
|
||||||
|
|
||||||
### Cards & Containers
|
A escala base é de `0.25rem` (`4px`). Prefira a escala padrão do Tailwind para
|
||||||
|
padding, gap e margens. O raio base é `0.7rem`, exposto pelas classes
|
||||||
|
`rounded-sm`, `rounded-md`, `rounded-lg` e `rounded-xl`.
|
||||||
|
|
||||||
#### Standard Card
|
Sombras também são tokens. Cards comuns usam `shadow-xs`; menus, tooltips e
|
||||||
- **Background:** `#FFFFFF`
|
modais podem subir de nível conforme a necessidade. Evite adicionar sombra forte
|
||||||
- **Border:** `1px solid #F0EEEC`
|
a cada bloco: bordas e diferença de superfície devem resolver a maior parte da
|
||||||
- **Border Radius:** `11.2px`
|
hierarquia.
|
||||||
- **Padding:** `24px`
|
|
||||||
- **Box Shadow:** `none`
|
|
||||||
- **Text Color:** `#2A2827`
|
|
||||||
- **Hover State:** Border color `#E8E3E0`; box-shadow `0px 4px 12px rgba(0, 0, 0, 0.08)`
|
|
||||||
|
|
||||||
#### Card with Top Border
|
## 6. Componentes
|
||||||
- **Background:** `#FFFFFF`
|
|
||||||
- **Border:** `1px solid #F0EEEC`
|
|
||||||
- **Border Radius:** `15.2px 15.2px 0px 0px` (top corners only)
|
|
||||||
- **Padding:** `24px`
|
|
||||||
- **Box Shadow:** `none`
|
|
||||||
- **Top Border Color:** `#FF7733` (3px height implied)
|
|
||||||
|
|
||||||
#### Surface Container (Header/Nav)
|
### Botões
|
||||||
- **Background:** `#FF7733`
|
|
||||||
- **Height:** `64px`
|
|
||||||
- **Padding:** `0px 24px`
|
|
||||||
- **Box Shadow:** `none`
|
|
||||||
- **Text Color:** `#FFFFFF`
|
|
||||||
- **Border:** `0px solid transparent`
|
|
||||||
|
|
||||||
#### Light Surface
|
Use [`Button`](./src/shared/components/ui/button.tsx) e suas variantes:
|
||||||
- **Background:** `#F8F6F4`
|
|
||||||
- **Border:** `0px solid transparent`
|
|
||||||
- **Border Radius:** `11.2px`
|
|
||||||
- **Padding:** `16px`
|
|
||||||
- **Box Shadow:** `none`
|
|
||||||
|
|
||||||
### Inputs & Forms
|
| Variante | Uso |
|
||||||
|
|---|---|
|
||||||
|
| `default` | Ação principal da tela ou do fluxo |
|
||||||
|
| `secondary` | Ação complementar |
|
||||||
|
| `outline` | Ação neutra com contorno |
|
||||||
|
| `ghost` | Ação discreta em barras e grupos |
|
||||||
|
| `link` | Ação textual |
|
||||||
|
| `destructive` | Exclusão ou operação irreversível |
|
||||||
|
| `navbar` | Ferramentas da navegação superior |
|
||||||
|
|
||||||
#### Text Input
|
Não coloque duas ações `default` competindo na mesma região. Para ícones sem
|
||||||
- **Background:** `#FFFFFF`
|
rótulo visível, inclua `aria-label` ou texto apenas para leitores de tela.
|
||||||
- **Border:** `1px solid #F0EEEC`
|
|
||||||
- **Border Radius:** `9.2px`
|
|
||||||
- **Padding:** `12px 16px`
|
|
||||||
- **Font Size:** `16px`
|
|
||||||
- **Text Color:** `#2A2827`
|
|
||||||
- **Line Height:** `24px`
|
|
||||||
- **Placeholder Color:** `#999890`
|
|
||||||
- **Focus State:** Border color `#FF7733`; box-shadow `0px 0px 0px 3px rgba(255, 119, 51, 0.1)`
|
|
||||||
- **Error State:** Border color `#F53F2D`; background `#FEF5F3`
|
|
||||||
- **Disabled State:** Background `#F8F6F4`; text color `#BFBAB7`; border color `#F0EEEC`
|
|
||||||
|
|
||||||
#### Select / Dropdown
|
### Cards
|
||||||
- **Background:** `#FFFFFF`
|
|
||||||
- **Border:** `1px solid #F0EEEC`
|
|
||||||
- **Border Radius:** `9.2px`
|
|
||||||
- **Padding:** `12px 16px`
|
|
||||||
- **Font Size:** `16px`
|
|
||||||
- **Text Color:** `#2A2827`
|
|
||||||
- **Focus State:** Border color `#FF7733`; outline `0px`
|
|
||||||
- **Hover State:** Background `#FAFAF8`
|
|
||||||
|
|
||||||
#### Checkbox & Radio
|
Use [`Card`](./src/shared/components/ui/card.tsx) para agrupar informações
|
||||||
- **Size:** `20px` × `20px`
|
relacionadas. O componente já define fundo, borda, sombra leve, raio e destaque
|
||||||
- **Border Radius:** `4px` (checkbox), `50%` (radio)
|
de hover. Não transforme todo conteúdo em card: listas densas e tabelas podem
|
||||||
- **Border:** `2px solid #F0EEEC`
|
usar uma única superfície.
|
||||||
- **Background:** `#FFFFFF`
|
|
||||||
- **Checked Background:** `#FF7733`
|
|
||||||
- **Checked Border:** `2px solid #FF7733`
|
|
||||||
- **Checked Icon Color:** `#FFFFFF`
|
|
||||||
- **Focus:** Border `2px solid #FF7733`; box-shadow `0px 0px 0px 3px rgba(255, 119, 51, 0.1)`
|
|
||||||
|
|
||||||
### Navigation
|
### Formulários
|
||||||
|
|
||||||
#### Primary Navigation
|
Campos devem usar os componentes compartilhados, como `Input`, `Select`,
|
||||||
- **Background:** `#FF7733`
|
`Checkbox`, `Switch` e `DatePicker`. Eles já aplicam foco com `ring`, estados
|
||||||
- **Height:** `64px`
|
desabilitados e integração visual com os temas. Sempre associe controles a
|
||||||
- **Padding:** `0px 48px`
|
`Label` e apresente erros próximos ao campo correspondente.
|
||||||
- **Display:** flex; align-items: center; gap `32px`
|
|
||||||
- **Link Color:** `#FFFFFF`
|
|
||||||
- **Link Font Size:** `16px`
|
|
||||||
- **Link Font Weight:** `400`
|
|
||||||
- **Link Hover:** Opacity `0.8`
|
|
||||||
- **Link Active:** Text decoration underline; opacity `1.0`
|
|
||||||
|
|
||||||
#### Secondary Navigation / Tabs
|
### Diálogos
|
||||||
- **Background:** `transparent`
|
|
||||||
- **Border Bottom:** `2px solid #F0EEEC`
|
|
||||||
- **Tab Padding:** `16px 24px`
|
|
||||||
- **Tab Color:** `#676260`
|
|
||||||
- **Tab Font Size:** `16px`
|
|
||||||
- **Tab Hover:** Color `#443732`
|
|
||||||
- **Tab Active:** Color `#FF7733`; border-bottom color `#FF7733`
|
|
||||||
|
|
||||||
#### Breadcrumb Navigation
|
Use [`Dialog`](./src/shared/components/ui/dialog.tsx) para tarefas focadas. Em
|
||||||
- **Font Size:** `14px`
|
mobile, o conteúdo respeita a largura disponível; em telas maiores, o modal pode
|
||||||
- **Color:** `#676260`
|
ganhar mais espaço. Botões do rodapé devem preservar a ordem e a hierarquia da
|
||||||
- **Separator:** `/` with `0px 8px` margin
|
ação principal.
|
||||||
- **Link Color:** `#443732`
|
|
||||||
- **Link Hover:** Color `#FF7733`
|
|
||||||
- **Current (Active):** Color `#2A2827`; font-weight `500`
|
|
||||||
|
|
||||||
### Badges & Status Indicators
|
### Feedback
|
||||||
|
|
||||||
#### Badge – Default
|
Use toast para retorno breve, `Alert` para contexto persistente e componentes em
|
||||||
- **Background:** `#F8F6F4`
|
[`src/shared/components/feedback/`](./src/shared/components/feedback/) para
|
||||||
- **Text Color:** `#443732`
|
estados vazios, status e confirmações. Textos visíveis ao usuário devem estar em
|
||||||
- **Padding:** `4px 12px`
|
português claro.
|
||||||
- **Border Radius:** `20px`
|
|
||||||
- **Font Size:** `12px`
|
|
||||||
- **Font Weight:** `500`
|
|
||||||
- **Border:** `0px solid transparent`
|
|
||||||
|
|
||||||
#### Badge – Success
|
## 7. Layout e navegação
|
||||||
- **Background:** `#E8F5F0`
|
|
||||||
- **Text Color:** `#0E9D6E`
|
|
||||||
- **Padding:** `4px 12px`
|
|
||||||
- **Border Radius:** `20px`
|
|
||||||
- **Font Size:** `12px`
|
|
||||||
- **Font Weight:** `500`
|
|
||||||
|
|
||||||
#### Badge – Warning
|
As páginas protegidas usam uma navbar fixa e um contêiner central com largura
|
||||||
- **Background:** `#FEF5E8`
|
máxima `max-w-8xl`, padding lateral responsivo e espaçamento vertical enxuto. A
|
||||||
- **Text Color:** `#F7A439`
|
navegação principal fica em
|
||||||
- **Padding:** `4px 12px`
|
[`src/shared/components/navigation/navbar/`](./src/shared/components/navigation/navbar/).
|
||||||
- **Border Radius:** `20px`
|
|
||||||
- **Font Size:** `12px`
|
|
||||||
- **Font Weight:** `500`
|
|
||||||
|
|
||||||
#### Badge – Error
|
Padrões:
|
||||||
- **Background:** `#FEF5F3`
|
|
||||||
- **Text Color:** `#F53F2D`
|
|
||||||
- **Padding:** `4px 12px`
|
|
||||||
- **Border Radius:** `20px`
|
|
||||||
- **Font Size:** `12px`
|
|
||||||
- **Font Weight:** `500`
|
|
||||||
|
|
||||||
## 5. Layout Principles
|
- telas do App Router devem continuar finas;
|
||||||
|
- conteúdo principal começa abaixo da navbar fixa (`pt-16`);
|
||||||
|
- use uma coluna em telas pequenas e expanda grids progressivamente;
|
||||||
|
- tabelas e gráficos devem preservar leitura em viewport estreita;
|
||||||
|
- ações essenciais precisam continuar alcançáveis por toque e teclado.
|
||||||
|
|
||||||
### Spacing System
|
## 8. Acessibilidade
|
||||||
- **Base Unit:** `4px`
|
|
||||||
- **Scale:** `4px`, `8px`, `12px`, `16px`, `24px`, `32px`, `48px`, `56px`, `64px`, `80px`, `96px`, `128px`
|
|
||||||
|
|
||||||
**Usage Contexts:**
|
- mantenha foco visível com os tokens `ring`;
|
||||||
- **4–8px:** Tight spacing within compact components (icon-text pairs, inline elements)
|
- use HTML semântico antes de adicionar ARIA;
|
||||||
- **12–16px:** Standard padding inside cards, inputs, and buttons
|
- não comunique estado apenas por cor;
|
||||||
- **24–32px:** Section gaps, spacing between components on a page
|
- associe labels a inputs;
|
||||||
- **48–64px:** Large section separations, hero spacing
|
- forneça nome acessível para botões de ícone;
|
||||||
- **80–128px:** Hero margins, page-level vertical rhythm
|
- confira contraste e navegação por teclado nos temas claro e escuro;
|
||||||
|
- mantenha áreas de toque confortáveis em mobile.
|
||||||
|
|
||||||
### Grid & Container
|
## 9. Checklist de revisão visual
|
||||||
- **Max Width:** `1440px` for full-width containers
|
|
||||||
- **Content Width:** `1152px` for typical page layouts
|
|
||||||
- **Column Strategy:** 12-column grid system; gutter `24px`
|
|
||||||
- **Container Padding:** `48px` on desktop (left + right)
|
|
||||||
- **Section Pattern:** Full-width containers with internal max-width constraint
|
|
||||||
|
|
||||||
### Whitespace Philosophy
|
- O componente compartilhado existente foi reutilizado?
|
||||||
OpenMonetis prioritizes breathing room and visual clarity. Whitespace is intentional and strategic—surrounding headings, separating card groups, and framing key messages. The warm neutral backgrounds (`#F8F6F4`, `#F5F2EF`) create natural visual separation without hard borders. Minimum margin between major sections is `64px` vertically; minimum padding inside containers is `16px`.
|
- As cores usam tokens semânticos?
|
||||||
|
- A tela funciona em tema claro e escuro?
|
||||||
### Border Radius Scale
|
- O layout continua legível em mobile?
|
||||||
- **Sharp Corners:** `0px` (utility container tops, category selectors)
|
- Foco, labels e nomes acessíveis estão presentes?
|
||||||
- **Subtle Radius:** `9.2px` (buttons, small inputs, icon buttons)
|
- Estados vazio, carregando, erro e sucesso foram considerados?
|
||||||
- **Standard Radius:** `11.2px` (cards, standard containers, modals)
|
- Valores financeiros continuam fáceis de comparar?
|
||||||
- **Rounded Top:** `15.2px 15.2px 0px 0px` (card headers, sheet-style containers)
|
|
||||||
- **Pill Shape:** `24px` (badges, full-rounded tags, avatar images)
|
|
||||||
- **Circle:** `50%` (avatar images, radial elements)
|
|
||||||
|
|
||||||
## 6. Depth & Elevation
|
|
||||||
|
|
||||||
| Level | Treatment | Use |
|
|
||||||
|-------|-----------|-----|
|
|
||||||
| Flat (None) | No shadow, `border: 1px solid #F0EEEC` | Default cards, inputs, containers; baseline surfaces |
|
|
||||||
| Subtle (sm) | `0px 1px 3px rgba(0, 0, 0, 0.06)` | Secondary buttons, hover states on light surfaces |
|
|
||||||
| Medium (md) | `0px 4px 12px rgba(0, 0, 0, 0.08)` | Elevated cards on hover, floating actions |
|
|
||||||
| Deep (lg) | `0px 10px 24px rgba(0, 0, 0, 0.12)` | Modals, dropdowns, popover menus |
|
|
||||||
|
|
||||||
**Shadow Philosophy:**
|
|
||||||
The design system uses restrained shadow treatment aligned with a flat-modern aesthetic. Shadows emerge subtly on interaction (hover, focus) rather than as default styling. The primary depth cue is border color (`#F0EEEC`), which maintains visual hierarchy without excessive z-depth. When shadows are used, they employ warm-tinted blacks (`rgba(0, 0, 0, 0.06–0.12)`) to harmonize with the warm neutral palette.
|
|
||||||
|
|
||||||
## 7. Do's and Don'ts
|
|
||||||
|
|
||||||
### Do
|
|
||||||
- Use the primary orange (`#FF7733`) exclusively for the most important call-to-action buttons
|
|
||||||
- Apply generous padding (`24px–48px`) around sections and inside cards for breathing room
|
|
||||||
- Stack elements vertically with `24–32px` gaps for clear visual rhythm
|
|
||||||
- Use warm grays (`#443732`, `#2A2827`) for all body text to maintain the warm aesthetic
|
|
||||||
- Apply `9.2px` border radius consistently to all interactive elements (buttons, inputs)
|
|
||||||
- Keep line heights at `1.4×` or greater for comfortable reading on body text
|
|
||||||
- Use semantic colors (`#0E9D6E` success, `#F7A439` warning, `#F53F2D` error) intentionally
|
|
||||||
- Test contrast ratios; maintain WCAG AA minimum (4.5:1 for body text)
|
|
||||||
- Use the `Inter` typeface exclusively for consistency
|
|
||||||
- Implement focus states with a `3px` colored outline or border
|
|
||||||
|
|
||||||
### Don't
|
|
||||||
- Don't use orange anywhere except primary CTAs and critical highlights
|
|
||||||
- Don't reduce padding below `12px` inside cards or `8px` inside compact buttons
|
|
||||||
- Don't use dark backgrounds (`#0F0D0C`) for body text on light surfaces; stick to `#2A2827` or `#443732`
|
|
||||||
- Don't apply shadows as default styling; reserve them for elevated states (hover, focus, modal)
|
|
||||||
- Don't mix border radius values on the same component type; stick to defined scale
|
|
||||||
- Don't increase line height above `1.6×` for headings; tighten for impact
|
|
||||||
- Don't use the error color (`#F53F2D`) for general emphasis; reserve for genuine errors
|
|
||||||
- Don't create new colors outside the palette; use opacity if gradation is needed
|
|
||||||
- Don't apply multiple shadows to a single element; layer a maximum of two shadow values
|
|
||||||
- Don't forget to include focus/keyboard navigation states on all interactive elements
|
|
||||||
|
|
||||||
## 8. Responsive Behavior
|
|
||||||
|
|
||||||
### Breakpoints
|
|
||||||
|
|
||||||
| Breakpoint | Width | Key Changes |
|
|
||||||
|-----------|-------|-------------|
|
|
||||||
| Mobile | `375px–599px` | Single column; container padding `16px`; font sizes reduce 1–2 sizes; gap scale halved |
|
|
||||||
| Tablet | `600px–1023px` | Two-column grid; container padding `32px`; button height `36px`; heading sizes reduce slightly |
|
|
||||||
| Desktop | `1024px+` | Full 12-column grid; container padding `48px`; full-scale typography; max-width `1440px` |
|
|
||||||
|
|
||||||
### Touch Targets
|
|
||||||
- **Minimum Interactive Size:** `44px` × `44px` for mobile; `40px` × `40px` for desktop
|
|
||||||
- **Button Padding:** `12px` vertical, `16px` horizontal (minimum)
|
|
||||||
- **Link Padding:** `6px` vertical, `8px` horizontal minimum
|
|
||||||
- **Icon Button:** `32px` × `32px` minimum (32px on mobile preferred)
|
|
||||||
- **Spacing Between Targets:** `8px` minimum to avoid accidental activation
|
|
||||||
|
|
||||||
### Collapsing Strategy
|
|
||||||
- **Navigation:** Horizontal nav on desktop collapses to hamburger menu on tablet; menu items stack vertically with `12px` gap
|
|
||||||
- **Grid:** 12-column layout on desktop → 6-column on tablet → 2-column (stacked) on mobile
|
|
||||||
- **Cards:** Three-column card layouts collapse to single column on mobile; padding reduces from `24px` to `16px`
|
|
||||||
- **Typography:** Display (60px) → 36px on tablet → 28px on mobile; body (20px) → 18px on tablet → 16px on mobile
|
|
||||||
- **Spacing:** All spacing scale values reduce by 25–33% on mobile (e.g., `24px` gap → `16px` on tablet, `12px` on mobile)
|
|
||||||
- **Buttons:** Full-width on mobile (padding `0px`); inline (auto-width) on desktop
|
|
||||||
- **Inputs:** Full-width on mobile; constrained width on desktop
|
|
||||||
|
|
||||||
## 9. Agent Prompt Guide
|
|
||||||
|
|
||||||
### Quick Color Reference
|
|
||||||
- **Primary CTA:** Warm Orange (`#FF7733`) — Buttons, highlights, key interactions
|
|
||||||
- **Primary Text:** Warm Brown (`#443732`) — Headings, strong emphasis
|
|
||||||
- **Secondary Text:** Dark Neutral (`#2A2827`) — Body text, card content
|
|
||||||
- **Background:** White (`#FFFFFF`) — Cards, primary surfaces
|
|
||||||
- **Background Alt:** Cream (`#FCF7F6`) — Alternative surfaces, light containers
|
|
||||||
- **Border:** Pale Gray (`#F0EEEC`) — Card borders, divider lines
|
|
||||||
- **Success:** Green (`#0E9D6E`) — Confirmation, positive states
|
|
||||||
- **Warning:** Amber (`#F7A439`) — Cautions, attention states
|
|
||||||
- **Error:** Red-Orange (`#F53F2D`) — Errors, destructive actions
|
|
||||||
- **Disabled:** Light Gray (`#E8E3E0`) — Inactive elements, inaccessible states
|
|
||||||
|
|
||||||
### Iteration Guide
|
|
||||||
1. **Always use `#FF7733` for primary buttons** and all main call-to-action elements; secondary buttons use `#FFFFFF` with `#F0EEEC` border
|
|
||||||
2. **Typography is always `Inter`** with weights 400 (body), 500 (emphasis), and 600 (headings); size hierarchy: 14 → 16 → 20 → 36 → 60px
|
|
||||||
3. **Spacing base is `4px`**; use multiples from the scale (8, 12, 16, 24, 32, 48, 64, 80, 96, 128px); never arbitrary values
|
|
||||||
4. **Border radius:** Apply `9.2px` to all buttons and inputs, `11.2px` to cards, `15.2px 15.2px 0px 0px` to top-bordered containers
|
|
||||||
5. **Cards default to `#FFFFFF` background with `1px solid #F0EEEC` border**; add shadow only on hover (0px 4px 12px rgba(0, 0, 0, 0.08))
|
|
||||||
6. **Form inputs:** Padding `12px 16px`, border `1px solid #F0EEEC`, focus state `border: 1px solid #FF7733` + `box-shadow: 0px 0px 0px 3px rgba(255, 119, 51, 0.1)`
|
|
||||||
7. **Navigation background is always `#FF7733`** with white text; links in content use `#443732` with underline on active
|
|
||||||
8. **Maintain 1.4× line height minimum for body text**; tighten headings to 1:1 or 1.2:1 ratio
|
|
||||||
9. **Contrast validation:** Text `#0F0D0C` or `#2A2827` on light backgrounds (WCAG AA); text `#FFFFFF` on `#FF7733` (WCAG AAA)
|
|
||||||
10. **Responsive collapse:** Reduce padding and font by 25% on mobile; stack multi-column layouts to single column; full-width buttons on mobile only
|
|
||||||
|
|||||||
56
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/)
|
||||||
@@ -36,6 +38,7 @@
|
|||||||
- [Backup](#-backup)
|
- [Backup](#-backup)
|
||||||
- [Storage S3 Compatível](#-storage-s3-compatível)
|
- [Storage S3 Compatível](#-storage-s3-compatível)
|
||||||
- [Variáveis de Ambiente](#-variáveis-de-ambiente)
|
- [Variáveis de Ambiente](#-variáveis-de-ambiente)
|
||||||
|
- [Design System](#-design-system)
|
||||||
- [Arquitetura](#-arquitetura)
|
- [Arquitetura](#-arquitetura)
|
||||||
- [Contribuindo](#-contribuindo)
|
- [Contribuindo](#-contribuindo)
|
||||||
- [Apoie o Projeto](#-apoie-o-projeto)
|
- [Apoie o Projeto](#-apoie-o-projeto)
|
||||||
@@ -62,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.
|
||||||
|
|
||||||
📊 **Dashboard e relatórios** — Widgets interativos de métricas, gráficos de evolução, comparativos por categoria, tendências, uso de cartões, top estabelecimentos. 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.
|
||||||
|
|
||||||
@@ -76,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.
|
||||||
|
|
||||||
@@ -86,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 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
|
||||||
|
|
||||||
@@ -94,6 +97,7 @@ A ideia é simples: ter um lugar onde consigo ver todas as minhas contas, cartõ
|
|||||||
- **PostgreSQL** + **Drizzle ORM**
|
- **PostgreSQL** + **Drizzle ORM**
|
||||||
- **Better Auth** (email/senha, OAuth, Passkeys/WebAuthn)
|
- **Better Auth** (email/senha, OAuth, Passkeys/WebAuthn)
|
||||||
- **shadcn/ui** (Radix UI) + **Tailwind CSS**
|
- **shadcn/ui** (Radix UI) + **Tailwind CSS**
|
||||||
|
- **Bricolage Grotesque** via `next/font`
|
||||||
- **Docker** (multi-stage build)
|
- **Docker** (multi-stage build)
|
||||||
- **Biome** (linting + formatting)
|
- **Biome** (linting + formatting)
|
||||||
- **Vercel AI SDK** (Claude, GPT, Gemini, MiniMax, OpenRouter, Ollama)
|
- **Vercel AI SDK** (Claude, GPT, Gemini, MiniMax, OpenRouter, Ollama)
|
||||||
@@ -449,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=
|
||||||
@@ -483,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:
|
||||||
@@ -504,6 +522,19 @@ Se o OpenMonetis estiver rodando dentro de um container Docker e o Ollama estive
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## 🎨 Design System
|
||||||
|
|
||||||
|
O OpenMonetis usa uma identidade visual própria com superfícies quentes, laranja
|
||||||
|
como cor de destaque, temas claro e escuro e tipografia Bricolage Grotesque. A
|
||||||
|
interface é construída com tokens semânticos em OKLCH, Tailwind CSS 4 e
|
||||||
|
componentes compartilhados baseados em shadcn/ui e Radix UI.
|
||||||
|
|
||||||
|
As regras de cores, tipografia, componentes, responsividade e acessibilidade
|
||||||
|
estão documentadas no [`DESIGN.md`](DESIGN.md). Use esse guia como referência ao
|
||||||
|
criar telas ou alterar componentes visuais.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## 🏗️ Arquitetura
|
## 🏗️ Arquitetura
|
||||||
|
|
||||||
O projeto segue arquitetura **feature-first** dentro de `src/`:
|
O projeto segue arquitetura **feature-first** dentro de `src/`:
|
||||||
@@ -592,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.11 -m "v2.7.11"
|
||||||
|
git push origin v2.7.11
|
||||||
|
```
|
||||||
|
|
||||||
|
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
|
||||||
|
|||||||
1
drizzle/0030_complete_umar.sql
Normal file
@@ -0,0 +1 @@
|
|||||||
|
ALTER TABLE "preferencias_usuario" ADD COLUMN "mostrar_resumo_lancamento" boolean DEFAULT true NOT NULL;
|
||||||
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;
|
||||||
2923
drizzle/meta/0030_snapshot.json
Normal file
2988
drizzle/meta/0031_snapshot.json
Normal file
2995
drizzle/meta/0032_snapshot.json
Normal file
3002
drizzle/meta/0033_snapshot.json
Normal file
@@ -204,6 +204,34 @@
|
|||||||
"when": 1777648189399,
|
"when": 1777648189399,
|
||||||
"tag": "0029_friendly_spitfire",
|
"tag": "0029_friendly_spitfire",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 30,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1780150535055,
|
||||||
|
"tag": "0030_complete_umar",
|
||||||
|
"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
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
56
package.json
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "openmonetis",
|
"name": "openmonetis",
|
||||||
"version": "2.7.0",
|
"version": "2.7.11",
|
||||||
"private": true,
|
"private": true,
|
||||||
"packageManager": "pnpm@11.1.3",
|
"packageManager": "pnpm@11.1.3",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
@@ -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.2.7",
|
||||||
"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": "6.0.3"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
3849
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 |
@@ -1,10 +1,10 @@
|
|||||||
import { Golos_Text } from "next/font/google";
|
import { Bricolage_Grotesque } from "next/font/google";
|
||||||
|
|
||||||
export const inter = Golos_Text({
|
export const bricolage = Bricolage_Grotesque({
|
||||||
subsets: ["latin"],
|
subsets: ["latin"],
|
||||||
display: "swap",
|
display: "swap",
|
||||||
variable: "--font-inter",
|
variable: "--font-bricolage",
|
||||||
fallback: ["ui-sans-serif", "system-ui"],
|
fallback: ["arial", "ui-sans-serif", "system-ui"],
|
||||||
weight: ["500", "600", "700"],
|
weight: ["500", "600", "700"],
|
||||||
preload: true,
|
preload: true,
|
||||||
});
|
});
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 571 KiB After Width: | Height: | Size: 350 KiB |
|
Before Width: | Height: | Size: 562 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 |
BIN
public/images/pwa-preview-dark.png
Normal file
|
After Width: | Height: | Size: 139 KiB |
|
Before Width: | Height: | Size: 88 KiB |
BIN
public/images/pwa-preview-light.png
Normal file
|
After Width: | Height: | Size: 137 KiB |
|
Before Width: | Height: | Size: 92 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,6 @@
|
|||||||
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 { 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";
|
||||||
|
|
||||||
@@ -26,11 +26,14 @@ export default async function Page({ searchParams }: PageProps) {
|
|||||||
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>
|
||||||
|
|||||||
@@ -27,6 +27,10 @@ export default async function Page({ searchParams }: PageProps) {
|
|||||||
const { dashboardData, preferences, quickActionOptions } =
|
const { dashboardData, preferences, quickActionOptions } =
|
||||||
await fetchDashboardPageData(user.id, selectedPeriod);
|
await fetchDashboardPageData(user.id, selectedPeriod);
|
||||||
const { dashboardWidgets } = preferences;
|
const { dashboardWidgets } = preferences;
|
||||||
|
const adminPayerSlug =
|
||||||
|
quickActionOptions.payerOptions.find(
|
||||||
|
(option) => option.value === quickActionOptions.defaultPayerId,
|
||||||
|
)?.slug ?? null;
|
||||||
|
|
||||||
const logoMappings = await prefetchLogoMappings(
|
const logoMappings = await prefetchLogoMappings(
|
||||||
user.id,
|
user.id,
|
||||||
@@ -37,7 +41,11 @@ 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 />
|
||||||
<DashboardMetricsCards metrics={dashboardData.metrics} />
|
<DashboardMetricsCards
|
||||||
|
metrics={dashboardData.metrics}
|
||||||
|
period={selectedPeriod}
|
||||||
|
adminPayerSlug={adminPayerSlug}
|
||||||
|
/>
|
||||||
<LogoPrefetchProvider mappings={logoMappings}>
|
<LogoPrefetchProvider mappings={logoMappings}>
|
||||||
<DashboardGridEditable
|
<DashboardGridEditable
|
||||||
data={dashboardData}
|
data={dashboardData}
|
||||||
|
|||||||
@@ -1,39 +1,125 @@
|
|||||||
|
import { Card, CardContent } from "@/shared/components/ui/card";
|
||||||
import { Skeleton } from "@/shared/components/ui/skeleton";
|
import { Skeleton } from "@/shared/components/ui/skeleton";
|
||||||
|
|
||||||
/**
|
const providers = [
|
||||||
* Loading state para a página de insights com IA
|
"openai",
|
||||||
*/
|
"anthropic",
|
||||||
|
"google",
|
||||||
|
"minimax",
|
||||||
|
"openrouter",
|
||||||
|
"ollama",
|
||||||
|
];
|
||||||
|
|
||||||
|
const summaryRows = ["period", "data-source"];
|
||||||
|
|
||||||
export default function InsightsLoading() {
|
export default function InsightsLoading() {
|
||||||
return (
|
return (
|
||||||
<main className="flex flex-col gap-6">
|
<main className="flex flex-col gap-6">
|
||||||
<div className="space-y-6 pt-4">
|
<Card className="flex w-full flex-row items-center justify-between gap-2 px-3 py-3 sm:px-4">
|
||||||
{/* Header */}
|
<div className="flex items-center gap-2">
|
||||||
|
<Skeleton className="size-8 bg-foreground/10" />
|
||||||
|
<Skeleton className="h-8 w-40 bg-foreground/10" />
|
||||||
|
<Skeleton className="size-8 bg-foreground/10" />
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<section className="space-y-4">
|
||||||
|
<div className="grid items-stretch gap-4 xl:grid-cols-[minmax(0,1fr)_340px]">
|
||||||
|
<div className="space-y-4">
|
||||||
|
<Card className="border-border/70 bg-card/95 shadow-sm">
|
||||||
|
<CardContent className="space-y-6">
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Skeleton className="h-10 w-64 rounded-md bg-foreground/10" />
|
<Skeleton className="h-8 w-64 bg-foreground/10" />
|
||||||
<Skeleton className="h-6 w-96 rounded-md bg-foreground/10" />
|
<Skeleton className="h-4 w-full max-w-2xl bg-foreground/10" />
|
||||||
|
<Skeleton className="h-4 w-3/4 max-w-xl bg-foreground/10" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Grid de insights */}
|
<div className="space-y-3">
|
||||||
<div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
|
|
||||||
{Array.from({ length: 4 }).map((_, i) => (
|
|
||||||
<div key={i} className="rounded-md border p-6 space-y-4">
|
|
||||||
<div className="flex items-start justify-between">
|
|
||||||
<div className="space-y-2 flex-1">
|
|
||||||
<Skeleton className="h-6 w-48 rounded-md bg-foreground/10" />
|
|
||||||
<Skeleton className="h-4 w-full rounded-md bg-foreground/10" />
|
|
||||||
<Skeleton className="h-4 w-3/4 rounded-md bg-foreground/10" />
|
|
||||||
</div>
|
|
||||||
<Skeleton className="size-8 rounded-full bg-foreground/10" />
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Skeleton className="h-3 w-full rounded-md bg-foreground/10" />
|
<Skeleton className="h-4 w-28 bg-foreground/10" />
|
||||||
<Skeleton className="h-3 w-full rounded-md bg-foreground/10" />
|
<Skeleton className="h-3 w-80 max-w-full bg-foreground/10" />
|
||||||
<Skeleton className="h-3 w-2/3 rounded-md bg-foreground/10" />
|
</div>
|
||||||
|
|
||||||
|
<div className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">
|
||||||
|
{providers.map((provider) => (
|
||||||
|
<div
|
||||||
|
className="flex min-h-24 items-start gap-3 rounded-2xl border p-4"
|
||||||
|
key={provider}
|
||||||
|
>
|
||||||
|
<Skeleton className="mt-1 size-4 shrink-0 rounded-full bg-foreground/10" />
|
||||||
|
<Skeleton className="size-8 shrink-0 rounded-full bg-foreground/10" />
|
||||||
|
<div className="flex-1 space-y-2">
|
||||||
|
<Skeleton className="h-4 w-20 bg-foreground/10" />
|
||||||
|
<Skeleton className="h-3 w-full bg-foreground/10" />
|
||||||
|
<Skeleton className="h-3 w-3/4 bg-foreground/10" />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card className="border-border/70 bg-card/95 shadow-sm">
|
||||||
|
<CardContent className="space-y-6">
|
||||||
|
<div className="space-y-3">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Skeleton className="h-4 w-32 bg-foreground/10" />
|
||||||
|
<Skeleton className="h-3 w-72 max-w-full bg-foreground/10" />
|
||||||
|
</div>
|
||||||
|
<Skeleton className="h-9 w-full max-w-72 bg-foreground/10" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between gap-3">
|
||||||
|
<Skeleton className="h-9 w-24 bg-foreground/10" />
|
||||||
|
<Skeleton className="h-9 w-32 bg-foreground/10" />
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Card className="border-border/70 bg-card/95 shadow-sm">
|
||||||
|
<CardContent className="flex flex-col gap-4">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<Skeleton className="size-9 rounded-xl bg-foreground/10" />
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Skeleton className="h-4 w-32 bg-foreground/10" />
|
||||||
|
<Skeleton className="h-3 w-24 bg-foreground/10" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Skeleton className="h-9 w-full bg-foreground/10" />
|
||||||
|
<Skeleton className="h-8 w-full bg-foreground/10" />
|
||||||
|
|
||||||
|
<div className="space-y-4">
|
||||||
|
{summaryRows.map((row) => (
|
||||||
|
<div className="flex gap-3" key={row}>
|
||||||
|
<Skeleton className="size-4 shrink-0 bg-foreground/10" />
|
||||||
|
<div className="flex-1 space-y-2">
|
||||||
|
<Skeleton className="h-3 w-24 bg-foreground/10" />
|
||||||
|
<Skeleton className="h-3 w-full bg-foreground/10" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-3">
|
||||||
|
<Skeleton className="h-3 w-32 bg-foreground/10" />
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<Skeleton className="size-8 rounded-full bg-foreground/10" />
|
||||||
|
<div className="flex-1 space-y-2">
|
||||||
|
<Skeleton className="h-4 w-20 bg-foreground/10" />
|
||||||
|
<Skeleton className="h-3 w-32 bg-foreground/10" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Skeleton className="h-20 w-full rounded-2xl bg-foreground/10" />
|
||||||
|
<Skeleton className="h-20 w-full rounded-2xl bg-foreground/10" />
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
</main>
|
</main>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
import { connection } from "next/server";
|
import { connection } from "next/server";
|
||||||
import { fetchDashboardNavbarData } from "@/features/dashboard/lib/navbar-queries";
|
import { fetchDashboardNavbarData } from "@/features/dashboard/lib/navbar-queries";
|
||||||
import { AppNavbar } from "@/shared/components/navigation/navbar/app-navbar";
|
import { AppNavbar } from "@/shared/components/navigation/navbar/app-navbar";
|
||||||
|
import { AppPreferencesProvider } from "@/shared/components/providers/app-preferences-provider";
|
||||||
import { LogoDevProvider } from "@/shared/components/providers/logo-dev-provider";
|
import { LogoDevProvider } from "@/shared/components/providers/logo-dev-provider";
|
||||||
import { PrivacyProvider } from "@/shared/components/providers/privacy-provider";
|
import { PrivacyProvider } from "@/shared/components/providers/privacy-provider";
|
||||||
import { getUserSession } from "@/shared/lib/auth/server";
|
import { getUserSession } from "@/shared/lib/auth/server";
|
||||||
import { isLogoDevEnabled } from "@/shared/lib/logo/server";
|
import { isLogoDevEnabled } from "@/shared/lib/logo/server";
|
||||||
|
import { fetchAppPreferences } from "@/shared/lib/preferences/queries";
|
||||||
|
|
||||||
export default async function DashboardLayout({
|
export default async function DashboardLayout({
|
||||||
children,
|
children,
|
||||||
@@ -13,17 +15,22 @@ export default async function DashboardLayout({
|
|||||||
}>) {
|
}>) {
|
||||||
await connection();
|
await connection();
|
||||||
const session = await getUserSession();
|
const session = await getUserSession();
|
||||||
const navbarData = await fetchDashboardNavbarData(session.user.id);
|
const [navbarData, appPreferences] = await Promise.all([
|
||||||
|
fetchDashboardNavbarData(session.user.id),
|
||||||
|
fetchAppPreferences(session.user.id),
|
||||||
|
]);
|
||||||
const logoDevEnabled = isLogoDevEnabled();
|
const logoDevEnabled = isLogoDevEnabled();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<LogoDevProvider enabled={logoDevEnabled}>
|
<LogoDevProvider enabled={logoDevEnabled}>
|
||||||
|
<AppPreferencesProvider {...appPreferences}>
|
||||||
<PrivacyProvider>
|
<PrivacyProvider>
|
||||||
<AppNavbar
|
<AppNavbar
|
||||||
user={{ ...session.user, image: session.user.image ?? null }}
|
user={{ ...session.user, image: session.user.image ?? null }}
|
||||||
payerAvatarUrl={navbarData.payerAvatarUrl}
|
payerAvatarUrl={navbarData.payerAvatarUrl}
|
||||||
inboxPendingCount={navbarData.inboxPendingCount}
|
inboxPendingCount={navbarData.inboxPendingCount}
|
||||||
notificationsSnapshot={navbarData.notificationsSnapshot}
|
notificationsSnapshot={navbarData.notificationsSnapshot}
|
||||||
|
financeLinks={navbarData.financeLinks}
|
||||||
/>
|
/>
|
||||||
<div className="relative flex flex-1 flex-col pt-16">
|
<div className="relative flex flex-1 flex-col pt-16">
|
||||||
<div className="@container/main flex flex-1 flex-col gap-2">
|
<div className="@container/main flex flex-1 flex-col gap-2">
|
||||||
@@ -33,6 +40,7 @@ export default async function DashboardLayout({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</PrivacyProvider>
|
</PrivacyProvider>
|
||||||
|
</AppPreferencesProvider>
|
||||||
</LogoDevProvider>
|
</LogoDevProvider>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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={
|
||||||
|
|||||||
61
src/app/(dashboard)/reports/installment-analysis/loading.tsx
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
import { Card, CardContent, CardHeader } from "@/shared/components/ui/card";
|
||||||
|
import { Skeleton } from "@/shared/components/ui/skeleton";
|
||||||
|
|
||||||
|
const installmentCards = ["first", "second", "third"];
|
||||||
|
|
||||||
|
export default function Loading() {
|
||||||
|
return (
|
||||||
|
<main className="flex flex-col gap-4 pb-8">
|
||||||
|
<Card className="border-none bg-primary/10 shadow-none">
|
||||||
|
<CardContent className="flex flex-col items-start justify-center gap-2 py-2">
|
||||||
|
<Skeleton className="h-4 w-64 bg-foreground/10" />
|
||||||
|
<Skeleton className="h-9 w-36 bg-foreground/10" />
|
||||||
|
<Skeleton className="h-4 w-32 bg-foreground/10" />
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Skeleton className="h-8 w-36 bg-foreground/10" />
|
||||||
|
|
||||||
|
<div className="grid grid-cols-1 gap-3 md:grid-cols-2 lg:grid-cols-3">
|
||||||
|
{installmentCards.map((card) => (
|
||||||
|
<Card key={card} className="overflow-hidden">
|
||||||
|
<CardHeader className="pb-0">
|
||||||
|
<div className="flex items-start gap-2">
|
||||||
|
<Skeleton className="mt-1 size-4 shrink-0 bg-foreground/10" />
|
||||||
|
<Skeleton className="size-10 shrink-0 rounded-full bg-foreground/10" />
|
||||||
|
<div className="flex-1 space-y-2">
|
||||||
|
<Skeleton className="h-5 w-32 bg-foreground/10" />
|
||||||
|
<Skeleton className="h-4 w-24 bg-foreground/10" />
|
||||||
|
</div>
|
||||||
|
<Skeleton className="h-5 w-16 rounded-full bg-foreground/10" />
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
|
||||||
|
<CardContent>
|
||||||
|
<div className="mb-4 grid grid-cols-2 gap-4 rounded-lg bg-primary/5 p-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Skeleton className="h-3 w-24 bg-foreground/10" />
|
||||||
|
<Skeleton className="h-6 w-20 bg-foreground/10" />
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col items-end gap-2">
|
||||||
|
<Skeleton className="h-3 w-16 bg-foreground/10" />
|
||||||
|
<Skeleton className="h-6 w-20 bg-foreground/10" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mb-4 space-y-2">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<Skeleton className="h-3 w-40 bg-foreground/10" />
|
||||||
|
<Skeleton className="h-3 w-16 bg-foreground/10" />
|
||||||
|
</div>
|
||||||
|
<Skeleton className="h-2.5 w-full bg-foreground/10" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Skeleton className="h-8 w-full bg-foreground/10" />
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -82,6 +82,15 @@ export default async function Page() {
|
|||||||
userPreferences?.transactionsColumnOrder ?? null
|
userPreferences?.transactionsColumnOrder ?? null
|
||||||
}
|
}
|
||||||
attachmentMaxSizeMb={userPreferences?.attachmentMaxSizeMb ?? 50}
|
attachmentMaxSizeMb={userPreferences?.attachmentMaxSizeMb ?? 50}
|
||||||
|
showTransactionSummary={
|
||||||
|
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>
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ export const metadata: Metadata = {
|
|||||||
description: DESCRIPTION,
|
description: DESCRIPTION,
|
||||||
images: [
|
images: [
|
||||||
{
|
{
|
||||||
url: "/images/dashboard-preview-light.webp",
|
url: "/images/dashboard-preview-light.png",
|
||||||
width: 1920,
|
width: 1920,
|
||||||
height: 1080,
|
height: 1080,
|
||||||
alt: "OpenMonetis — Dashboard de finanças pessoais",
|
alt: "OpenMonetis — Dashboard de finanças pessoais",
|
||||||
@@ -49,7 +49,7 @@ export const metadata: Metadata = {
|
|||||||
card: "summary_large_image",
|
card: "summary_large_image",
|
||||||
title: TITLE,
|
title: TITLE,
|
||||||
description: DESCRIPTION,
|
description: DESCRIPTION,
|
||||||
images: ["/images/dashboard-preview-light.webp"],
|
images: ["/images/dashboard-preview-light.png"],
|
||||||
},
|
},
|
||||||
robots: {
|
robots: {
|
||||||
index: true,
|
index: true,
|
||||||
|
|||||||
@@ -86,7 +86,7 @@ export async function POST(request: Request) {
|
|||||||
const body = await request.json();
|
const body = await request.json();
|
||||||
const { items } = inboxBatchSchema.parse(body);
|
const { items } = inboxBatchSchema.parse(body);
|
||||||
|
|
||||||
// Processar todos os itens em paralelo
|
// lançar todos os itens em paralelo
|
||||||
const settled = await Promise.allSettled(
|
const settled = await Promise.allSettled(
|
||||||
items.map((item) =>
|
items.map((item) =>
|
||||||
db
|
db
|
||||||
@@ -119,7 +119,7 @@ export async function POST(request: Request) {
|
|||||||
return {
|
return {
|
||||||
clientId: item?.clientId,
|
clientId: item?.clientId,
|
||||||
success: false,
|
success: false,
|
||||||
error: "Erro ao processar notificação",
|
error: "Erro ao lançar notificação",
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -160,7 +160,7 @@ export async function POST(request: Request) {
|
|||||||
|
|
||||||
console.error("[API] Error creating batch inbox items:", error);
|
console.error("[API] Error creating batch inbox items:", error);
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: "Erro ao processar notificações" },
|
{ error: "Erro ao lançar notificações" },
|
||||||
{ status: 500 },
|
{ status: 500 },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -127,7 +127,7 @@ export async function POST(request: Request) {
|
|||||||
|
|
||||||
console.error("[API] Error creating inbox item:", error);
|
console.error("[API] Error creating inbox item:", error);
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: "Erro ao processar notificação" },
|
{ error: "Erro ao lançar notificação" },
|
||||||
{ status: 500 },
|
{ status: 500 },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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(31.987% 0.00462 39.069);
|
--border: oklch(29.675% 0.01144 67.3);
|
||||||
--input: var(--border);
|
--input: var(--border);
|
||||||
--ring: var(--primary);
|
--ring: var(--primary);
|
||||||
|
|
||||||
@@ -170,7 +170,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
@theme inline {
|
@theme inline {
|
||||||
--default-font-family: var(--font-inter);
|
--default-font-family: var(--font-bricolage);
|
||||||
--color-background: var(--background);
|
--color-background: var(--background);
|
||||||
--color-foreground: var(--foreground);
|
--color-foreground: var(--foreground);
|
||||||
--color-card: var(--card);
|
--color-card: var(--card);
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { QueryProvider } from "@/shared/components/providers/query-provider";
|
|||||||
import { ThemeProvider } from "@/shared/components/providers/theme-provider";
|
import { ThemeProvider } from "@/shared/components/providers/theme-provider";
|
||||||
import { Toaster } from "@/shared/components/ui/sonner";
|
import { Toaster } from "@/shared/components/ui/sonner";
|
||||||
import "./globals.css";
|
import "./globals.css";
|
||||||
import { inter } from "@/public/fonts/font_index";
|
import { bricolage } from "@/public/fonts/font_index";
|
||||||
|
|
||||||
export const metadata: Metadata = {
|
export const metadata: Metadata = {
|
||||||
title: {
|
title: {
|
||||||
@@ -24,7 +24,7 @@ export default function RootLayout({
|
|||||||
<html
|
<html
|
||||||
data-scroll-behavior="smooth"
|
data-scroll-behavior="smooth"
|
||||||
lang="pt-BR"
|
lang="pt-BR"
|
||||||
className={`${inter.variable}`}
|
className={`${bricolage.className}`}
|
||||||
suppressHydrationWarning
|
suppressHydrationWarning
|
||||||
>
|
>
|
||||||
<head>
|
<head>
|
||||||
|
|||||||
@@ -154,6 +154,15 @@ export const userPreferences = pgTable("preferencias_usuario", {
|
|||||||
string[] | null
|
string[] | null
|
||||||
>(),
|
>(),
|
||||||
attachmentMaxSizeMb: integer("attachment_max_size_mb").notNull().default(50),
|
attachmentMaxSizeMb: integer("attachment_max_size_mb").notNull().default(50),
|
||||||
|
showTransactionSummary: boolean("mostrar_resumo_lancamento")
|
||||||
|
.notNull()
|
||||||
|
.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[];
|
||||||
@@ -495,7 +504,7 @@ export const inboxItems = pgTable(
|
|||||||
withTimezone: true,
|
withTimezone: true,
|
||||||
}).notNull(),
|
}).notNull(),
|
||||||
|
|
||||||
// Dados parseados (editáveis pelo usuário antes de processar)
|
// Dados parseados (editáveis pelo usuário antes de lançar)
|
||||||
parsedName: text("parsed_name"), // Nome do estabelecimento
|
parsedName: text("parsed_name"), // Nome do estabelecimento
|
||||||
parsedAmount: numeric("parsed_amount", { precision: 12, scale: 2 }),
|
parsedAmount: numeric("parsed_amount", { precision: 12, scale: 2 }),
|
||||||
|
|
||||||
@@ -844,11 +853,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 }) => ({
|
||||||
@@ -969,6 +979,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",
|
||||||
{
|
{
|
||||||
@@ -1041,6 +1069,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(
|
||||||
@@ -1057,8 +1086,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>
|
||||||
@@ -82,7 +86,7 @@ export function AccountStatementCard({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Linha 2 — saldo final (hero) */}
|
{/* Linha 2 — saldo final (hero) */}
|
||||||
<div className="space-y-4">
|
<div className="space-y-3">
|
||||||
<p className="text-sm text-muted-foreground ">
|
<p className="text-sm text-muted-foreground ">
|
||||||
Saldo ao final do período
|
Saldo ao final do período
|
||||||
</p>
|
</p>
|
||||||
|
|||||||
@@ -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 };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -81,6 +81,8 @@ const renderLancamento = (
|
|||||||
|
|
||||||
const renderBoleto = (event: Extract<CalendarEvent, { type: "boleto" }>) => {
|
const renderBoleto = (event: Extract<CalendarEvent, { type: "boleto" }>) => {
|
||||||
const isPaid = Boolean(event.transaction.isSettled);
|
const isPaid = Boolean(event.transaction.isSettled);
|
||||||
|
const isIncome = event.transaction.transactionType === "Receita";
|
||||||
|
const settlementLabel = isIncome ? "Recebido" : "Pago";
|
||||||
const dueDateLabel = formatFinancialDateLabel(
|
const dueDateLabel = formatFinancialDateLabel(
|
||||||
event.transaction.dueDate,
|
event.transaction.dueDate,
|
||||||
"Vence em",
|
"Vence em",
|
||||||
@@ -89,7 +91,7 @@ const renderBoleto = (event: Extract<CalendarEvent, { type: "boleto" }>) => {
|
|||||||
const paymentDateLabel = isPaid
|
const paymentDateLabel = isPaid
|
||||||
? formatFinancialDateLabel(
|
? formatFinancialDateLabel(
|
||||||
event.transaction.boletoPaymentDate,
|
event.transaction.boletoPaymentDate,
|
||||||
"Pago em",
|
`${settlementLabel} em`,
|
||||||
DATE_FORMAT,
|
DATE_FORMAT,
|
||||||
)
|
)
|
||||||
: null;
|
: null;
|
||||||
@@ -109,7 +111,9 @@ const renderBoleto = (event: Extract<CalendarEvent, { type: "boleto" }>) => {
|
|||||||
<span className="text-success">{paymentDateLabel}</span>
|
<span className="text-success">{paymentDateLabel}</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<Badge variant="outline">{isPaid ? "Pago" : "Pendente"}</Badge>
|
<Badge variant="outline">
|
||||||
|
{isPaid ? settlementLabel : "Pendente"}
|
||||||
|
</Badge>
|
||||||
</div>
|
</div>
|
||||||
<MoneyValues
|
<MoneyValues
|
||||||
className="font-medium whitespace-nowrap"
|
className="font-medium whitespace-nowrap"
|
||||||
|
|||||||
@@ -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 ??
|
||||||
|
|||||||
@@ -89,7 +89,7 @@ export function CategoryDetailHeader({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid gap-3 md:grid-cols-3">
|
<div className="grid gap-3 md:grid-cols-3">
|
||||||
<div className="rounded-md border border-dashed bg-muted/20 px-3 py-3">
|
<div className="rounded-lg border p-3">
|
||||||
<p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
|
<p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
|
||||||
Total em {currentPeriodLabel}
|
Total em {currentPeriodLabel}
|
||||||
</p>
|
</p>
|
||||||
@@ -98,7 +98,7 @@ export function CategoryDetailHeader({
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="rounded-md border border-dashed bg-muted/20 px-3 py-3">
|
<div className="rounded-lg border p-3">
|
||||||
<p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
|
<p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
|
||||||
Total em {previousPeriodLabel}
|
Total em {previousPeriodLabel}
|
||||||
</p>
|
</p>
|
||||||
@@ -107,7 +107,7 @@ export function CategoryDetailHeader({
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="rounded-md border border-dashed bg-muted/20 px-3 py-3">
|
<div className="rounded-lg border p-3">
|
||||||
<p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
|
<p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
|
||||||
Variação
|
Variação
|
||||||
</p>
|
</p>
|
||||||
|
|||||||
@@ -1,18 +1,28 @@
|
|||||||
import type { DashboardBill } from "@/features/dashboard/bills/bills-queries";
|
import type { DashboardBill } from "@/features/dashboard/bills/bills-queries";
|
||||||
import type { PaymentDialogState } from "@/features/dashboard/payments/use-payment-dialog-controller";
|
import type { PaymentDialogState } from "@/features/dashboard/payments/use-payment-dialog-controller";
|
||||||
import { getBusinessDateString, isDateOnlyPast } from "@/shared/utils/date";
|
import {
|
||||||
|
getBusinessDateString,
|
||||||
|
isDateOnlyPast,
|
||||||
|
parseUtcDateString,
|
||||||
|
toDateOnlyString,
|
||||||
|
} from "@/shared/utils/date";
|
||||||
import {
|
import {
|
||||||
buildFinancialStatusLabel,
|
buildFinancialStatusLabel,
|
||||||
buildRelativeFinancialStatusLabel,
|
buildRelativeFinancialStatusLabel,
|
||||||
formatFinancialDateLabel,
|
formatFinancialDateLabel,
|
||||||
|
formatRelativeFinancialDateLabel,
|
||||||
} from "@/shared/utils/financial-dates";
|
} from "@/shared/utils/financial-dates";
|
||||||
|
|
||||||
export type BillDialogState = PaymentDialogState;
|
export type BillDialogState = PaymentDialogState;
|
||||||
type BillStatusDateItem = Pick<
|
type BillStatusDateItem = Pick<
|
||||||
DashboardBill,
|
DashboardBill,
|
||||||
"dueDate" | "boletoPaymentDate" | "isSettled"
|
"dueDate" | "boletoPaymentDate" | "isSettled" | "transactionType"
|
||||||
>;
|
>;
|
||||||
|
|
||||||
|
export const isIncomeBill = (bill: Pick<DashboardBill, "transactionType">) => {
|
||||||
|
return bill.transactionType === "Receita";
|
||||||
|
};
|
||||||
|
|
||||||
export const formatBillDateLabel = (value: string | null, prefix?: string) => {
|
export const formatBillDateLabel = (value: string | null, prefix?: string) => {
|
||||||
return formatFinancialDateLabel(value, prefix);
|
return formatFinancialDateLabel(value, prefix);
|
||||||
};
|
};
|
||||||
@@ -22,10 +32,15 @@ export const buildBillStatusLabel = (bill: BillStatusDateItem) => {
|
|||||||
isSettled: bill.isSettled,
|
isSettled: bill.isSettled,
|
||||||
dueDate: bill.dueDate,
|
dueDate: bill.dueDate,
|
||||||
paidAt: bill.boletoPaymentDate,
|
paidAt: bill.boletoPaymentDate,
|
||||||
|
paidPrefix: isIncomeBill(bill) ? "Recebido em" : "Pago em",
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
export const buildBillWidgetStatusLabel = (bill: BillStatusDateItem) => {
|
export const buildBillWidgetStatusLabel = (bill: BillStatusDateItem) => {
|
||||||
|
if (bill.isSettled && isIncomeBill(bill)) {
|
||||||
|
return formatRelativeFinancialDateLabel(bill.boletoPaymentDate, "received");
|
||||||
|
}
|
||||||
|
|
||||||
return buildRelativeFinancialStatusLabel({
|
return buildRelativeFinancialStatusLabel({
|
||||||
isSettled: bill.isSettled,
|
isSettled: bill.isSettled,
|
||||||
dueDate: bill.dueDate,
|
dueDate: bill.dueDate,
|
||||||
@@ -43,6 +58,34 @@ export const isBillOverdue = (bill: DashboardBill) => {
|
|||||||
return isDateOnlyPast(bill.dueDate);
|
return isDateOnlyPast(bill.dueDate);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const formatBillWidgetOverdueLabel = (
|
||||||
|
bill: Pick<DashboardBill, "dueDate" | "isSettled" | "transactionType">,
|
||||||
|
): string | null => {
|
||||||
|
if (bill.isSettled) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const dueDateValue = toDateOnlyString(bill.dueDate);
|
||||||
|
const todayValue = getBusinessDateString();
|
||||||
|
if (!dueDateValue || dueDateValue >= todayValue) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const dueDate = parseUtcDateString(dueDateValue);
|
||||||
|
const today = parseUtcDateString(todayValue);
|
||||||
|
if (!dueDate || !today) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const overdueDays = Math.round(
|
||||||
|
(today.getTime() - dueDate.getTime()) / (24 * 60 * 60 * 1000),
|
||||||
|
);
|
||||||
|
const overdueLabel = isIncomeBill(bill) ? "Atrasada" : "Atrasado";
|
||||||
|
return overdueDays === 1
|
||||||
|
? `${overdueLabel} · venceu ontem`
|
||||||
|
: `${overdueLabel} · venceu há ${overdueDays} dias`;
|
||||||
|
};
|
||||||
|
|
||||||
export const getBillStatusBadgeVariant = (
|
export const getBillStatusBadgeVariant = (
|
||||||
statusLabel: string,
|
statusLabel: string,
|
||||||
): "success" | "info" => {
|
): "success" | "info" => {
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ export type DashboardBill = {
|
|||||||
boletoPaymentDate: string | null;
|
boletoPaymentDate: string | null;
|
||||||
isSettled: boolean;
|
isSettled: boolean;
|
||||||
accountId: string | null;
|
accountId: string | null;
|
||||||
|
transactionType: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type BillPaymentAccountOption = {
|
export type BillPaymentAccountOption = {
|
||||||
|
|||||||
@@ -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: {
|
||||||
|
|||||||
@@ -1,11 +1,14 @@
|
|||||||
import { RiCheckboxCircleFill, RiExternalLinkLine } from "@remixicon/react";
|
import { RiCheckboxCircleFill } from "@remixicon/react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import {
|
import {
|
||||||
buildBillStatusLabel,
|
buildBillStatusLabel,
|
||||||
buildBillWidgetStatusLabel,
|
buildBillWidgetStatusLabel,
|
||||||
|
formatBillWidgetOverdueLabel,
|
||||||
isBillOverdue,
|
isBillOverdue,
|
||||||
|
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";
|
||||||
@@ -36,40 +39,36 @@ export function BillListItem({ bill, period, onPay }: BillListItemProps) {
|
|||||||
const statusLabel = buildBillWidgetStatusLabel(bill);
|
const statusLabel = buildBillWidgetStatusLabel(bill);
|
||||||
const absoluteStatusLabel = buildBillStatusLabel(bill);
|
const absoluteStatusLabel = buildBillStatusLabel(bill);
|
||||||
const overdue = isBillOverdue(bill);
|
const overdue = isBillOverdue(bill);
|
||||||
|
const income = isIncomeBill(bill);
|
||||||
|
const overdueLabel = formatBillWidgetOverdueLabel(bill);
|
||||||
const statusTooltipLabel =
|
const statusTooltipLabel =
|
||||||
statusLabel && statusLabel !== absoluteStatusLabel
|
overdueLabel || (statusLabel && statusLabel !== absoluteStatusLabel)
|
||||||
? absoluteStatusLabel
|
? absoluteStatusLabel
|
||||||
: null;
|
: null;
|
||||||
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>
|
||||||
<RiExternalLinkLine
|
|
||||||
className="size-3 shrink-0 text-muted-foreground"
|
|
||||||
aria-hidden
|
|
||||||
/>
|
|
||||||
</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",
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{statusLabel}
|
{overdueLabel ?? statusLabel}
|
||||||
</span>
|
</span>
|
||||||
</TooltipTrigger>
|
</TooltipTrigger>
|
||||||
<TooltipContent side="top">
|
<TooltipContent side="top">
|
||||||
@@ -79,11 +78,11 @@ 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",
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{statusLabel}
|
{overdueLabel ?? statusLabel}
|
||||||
</span>
|
</span>
|
||||||
)
|
)
|
||||||
) : null}
|
) : null}
|
||||||
@@ -91,31 +90,37 @@ 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 ? (
|
||||||
|
<span className={`${styles.trailingMeta} text-success`}>
|
||||||
|
<RiCheckboxCircleFill className="size-3.5" />{" "}
|
||||||
|
{income ? "Recebido" : "Pago"}
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
size="sm"
|
size="sm"
|
||||||
variant="link"
|
variant="link"
|
||||||
className="h-auto p-0 disabled:opacity-100"
|
className={styles.actionButton}
|
||||||
disabled={bill.isSettled}
|
|
||||||
onClick={() => onPay(bill.id)}
|
onClick={() => onPay(bill.id)}
|
||||||
>
|
>
|
||||||
{bill.isSettled ? (
|
{overdue ? (
|
||||||
<span className="flex items-center gap-0.5 text-success">
|
|
||||||
<RiCheckboxCircleFill className="size-3.5" /> Pago
|
|
||||||
</span>
|
|
||||||
) : overdue ? (
|
|
||||||
<span className="overdue-blink">
|
<span className="overdue-blink">
|
||||||
<span className="overdue-blink-primary text-destructive">
|
<span className="overdue-blink-primary text-destructive">
|
||||||
Atrasado
|
{income ? "Atrasada" : "Atrasado"}
|
||||||
</span>
|
</span>
|
||||||
<span className="overdue-blink-secondary">Pagar</span>
|
<span className="overdue-blink-secondary">
|
||||||
|
{income ? "Receber" : "Pagar"}
|
||||||
</span>
|
</span>
|
||||||
|
</span>
|
||||||
|
) : income ? (
|
||||||
|
"Receber"
|
||||||
) : (
|
) : (
|
||||||
"Pagar"
|
"Pagar"
|
||||||
)}
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</li>
|
</li>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import {
|
|||||||
type BillDialogState,
|
type BillDialogState,
|
||||||
formatBillDateLabel,
|
formatBillDateLabel,
|
||||||
getBillStatusBadgeVariant,
|
getBillStatusBadgeVariant,
|
||||||
|
isIncomeBill,
|
||||||
} from "@/features/dashboard/bills/bills-helpers";
|
} from "@/features/dashboard/bills/bills-helpers";
|
||||||
import type {
|
import type {
|
||||||
BillPaymentAccountOption,
|
BillPaymentAccountOption,
|
||||||
@@ -66,11 +67,13 @@ export function BillPaymentDialog({
|
|||||||
onConfirm,
|
onConfirm,
|
||||||
}: BillPaymentDialogProps) {
|
}: BillPaymentDialogProps) {
|
||||||
const isProcessing = modalState === "processing" || isPending;
|
const isProcessing = modalState === "processing" || isPending;
|
||||||
|
const income = bill ? isIncomeBill(bill) : false;
|
||||||
|
const settlementLabel = income ? "Recebido" : "Pago";
|
||||||
const dueLabel = bill
|
const dueLabel = bill
|
||||||
? formatBillDateLabel(bill.dueDate, "Vencimento:")
|
? formatBillDateLabel(bill.dueDate, "Vencimento:")
|
||||||
: null;
|
: null;
|
||||||
const paidLabel = bill
|
const paidLabel = bill
|
||||||
? formatBillDateLabel(bill.boletoPaymentDate, "Pago em:")
|
? formatBillDateLabel(bill.boletoPaymentDate, `${settlementLabel} em:`)
|
||||||
: null;
|
: null;
|
||||||
const isBillPending = bill ? !bill.isSettled : false;
|
const isBillPending = bill ? !bill.isSettled : false;
|
||||||
const paymentDateValue = paymentDate.toISOString().split("T")[0] ?? "";
|
const paymentDateValue = paymentDate.toISOString().split("T")[0] ?? "";
|
||||||
@@ -103,8 +106,8 @@ export function BillPaymentDialog({
|
|||||||
>
|
>
|
||||||
{modalState === "success" ? (
|
{modalState === "success" ? (
|
||||||
<PaymentSuccess
|
<PaymentSuccess
|
||||||
title="Pagamento registrado!"
|
title={income ? "Recebimento registrado!" : "Pagamento registrado!"}
|
||||||
description="Atualizamos o status do boleto para pago. Em instantes ele aparecerá como baixado no histórico."
|
description={`Atualizamos o status do boleto para ${income ? "recebido" : "pago"}. Em instantes ele aparecerá como baixado no histórico.`}
|
||||||
onClose={onClose}
|
onClose={onClose}
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
@@ -112,10 +115,12 @@ export function BillPaymentDialog({
|
|||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
<div className="mb-1 flex items-center gap-3">
|
<div className="mb-1 flex items-center gap-3">
|
||||||
<div>
|
<div>
|
||||||
<DialogTitle>Confirmar pagamento</DialogTitle>
|
<DialogTitle>
|
||||||
|
{income ? "Confirmar recebimento" : "Confirmar pagamento"}
|
||||||
|
</DialogTitle>
|
||||||
<DialogDescription className="mt-1 text-xs">
|
<DialogDescription className="mt-1 text-xs">
|
||||||
{isBillPending
|
{isBillPending
|
||||||
? "Escolha a conta de origem e a data em que o boleto foi pago."
|
? `Escolha a conta de ${income ? "destino" : "origem"} e a data em que o boleto foi ${income ? "recebido" : "pago"}.`
|
||||||
: "Boleto"}
|
: "Boleto"}
|
||||||
</DialogDescription>
|
</DialogDescription>
|
||||||
</div>
|
</div>
|
||||||
@@ -158,12 +163,15 @@ export function BillPaymentDialog({
|
|||||||
<div className="flex items-center gap-1.5 text-muted-foreground">
|
<div className="flex items-center gap-1.5 text-muted-foreground">
|
||||||
<RiCalendarLine className="size-3.5" />
|
<RiCalendarLine className="size-3.5" />
|
||||||
<span className="text-xs font-medium uppercase">
|
<span className="text-xs font-medium uppercase">
|
||||||
{bill.isSettled ? "Pago em" : "Vencimento"}
|
{bill.isSettled
|
||||||
|
? `${settlementLabel} em`
|
||||||
|
: "Vencimento"}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<p className="font-semibold">
|
<p className="font-semibold">
|
||||||
{bill.isSettled
|
{bill.isSettled
|
||||||
? (paidLabel?.replace("Pago em: ", "") ?? "—")
|
? (paidLabel?.replace(`${settlementLabel} em: `, "") ??
|
||||||
|
"—")
|
||||||
: (dueLabel?.replace("Vencimento: ", "") ?? "—")}
|
: (dueLabel?.replace("Vencimento: ", "") ?? "—")}
|
||||||
</p>
|
</p>
|
||||||
</Card>
|
</Card>
|
||||||
@@ -175,7 +183,7 @@ export function BillPaymentDialog({
|
|||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="bill-widget-payment-account">
|
<Label htmlFor="bill-widget-payment-account">
|
||||||
Conta de pagamento
|
Conta de {income ? "recebimento" : "pagamento"}
|
||||||
</Label>
|
</Label>
|
||||||
<Select
|
<Select
|
||||||
value={paymentAccountId}
|
value={paymentAccountId}
|
||||||
@@ -212,7 +220,7 @@ export function BillPaymentDialog({
|
|||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="bill-widget-payment-date">
|
<Label htmlFor="bill-widget-payment-date">
|
||||||
Data do pagamento
|
Data do {income ? "recebimento" : "pagamento"}
|
||||||
</Label>
|
</Label>
|
||||||
<DatePicker
|
<DatePicker
|
||||||
id="bill-widget-payment-date"
|
id="bill-widget-payment-date"
|
||||||
@@ -231,8 +239,8 @@ export function BillPaymentDialog({
|
|||||||
<span className="text-sm text-muted-foreground">
|
<span className="text-sm text-muted-foreground">
|
||||||
Status atual
|
Status atual
|
||||||
</span>
|
</span>
|
||||||
<Badge variant={getBillStatusBadgeVariant("Pago")}>
|
<Badge variant={getBillStatusBadgeVariant(settlementLabel)}>
|
||||||
Pago
|
{settlementLabel}
|
||||||
</Badge>
|
</Badge>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ export function BillsList({ bills, period, onPay }: BillsListProps) {
|
|||||||
<WidgetEmptyState
|
<WidgetEmptyState
|
||||||
icon={<RiBarcodeFill className="size-6 text-muted-foreground" />}
|
icon={<RiBarcodeFill className="size-6 text-muted-foreground" />}
|
||||||
title="Nenhum boleto cadastrado para o período selecionado"
|
title="Nenhum boleto cadastrado para o período selecionado"
|
||||||
description="Cadastre boletos para monitorar os pagamentos aqui."
|
description="Cadastre boletos para monitorar os vencimentos aqui."
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,9 +41,7 @@ export function BillsWidgetView({
|
|||||||
}: BillsWidgetViewProps) {
|
}: BillsWidgetViewProps) {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="flex flex-col gap-4">
|
|
||||||
<BillsList bills={bills} period={period} onPay={onOpenPaymentDialog} />
|
<BillsList bills={bills} period={period} onPay={onOpenPaymentDialog} />
|
||||||
</div>
|
|
||||||
|
|
||||||
<BillPaymentDialog
|
<BillPaymentDialog
|
||||||
bill={selectedBill}
|
bill={selectedBill}
|
||||||
|
|||||||
@@ -96,7 +96,7 @@ export function CategoryBreakdownChart({
|
|||||||
}, [categories, chartConfig]);
|
}, [categories, chartConfig]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center gap-4">
|
<div className="flex flex-col items-center gap-4 sm:flex-row">
|
||||||
<ChartContainer config={chartConfig} className="h-[280px] flex-1">
|
<ChartContainer config={chartConfig} className="h-[280px] flex-1">
|
||||||
<PieChart>
|
<PieChart>
|
||||||
<Pie
|
<Pie
|
||||||
@@ -143,7 +143,7 @@ export function CategoryBreakdownChart({
|
|||||||
</PieChart>
|
</PieChart>
|
||||||
</ChartContainer>
|
</ChartContainer>
|
||||||
|
|
||||||
<div className="min-w-[140px] flex flex-col gap-2">
|
<div className="grid w-full grid-cols-2 gap-2 sm:min-w-[140px] sm:w-auto sm:grid-cols-1">
|
||||||
{chartData.map((entry, index) => (
|
{chartData.map((entry, index) => (
|
||||||
<div key={`legend-${index}`} className="flex items-center gap-2">
|
<div key={`legend-${index}`} className="flex items-center gap-2">
|
||||||
<div
|
<div
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { RiExternalLinkLine } from "@remixicon/react";
|
|
||||||
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";
|
||||||
@@ -11,13 +11,14 @@ type CategoryBreakdownListItemConfig = {
|
|||||||
shareLabel: string;
|
shareLabel: string;
|
||||||
percentageDigits: number;
|
percentageDigits: number;
|
||||||
positiveTrend: "up" | "down";
|
positiveTrend: "up" | "down";
|
||||||
includeBudgetAmount: boolean;
|
showBudget: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
type CategoryBreakdownListItemProps = {
|
type CategoryBreakdownListItemProps = {
|
||||||
category: DashboardCategoryBreakdownItem;
|
category: DashboardCategoryBreakdownItem;
|
||||||
periodParam: string;
|
periodParam: string;
|
||||||
config: CategoryBreakdownListItemConfig;
|
config: CategoryBreakdownListItemConfig;
|
||||||
|
position: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
const formatPercentage = (value: number, digits: number) =>
|
const formatPercentage = (value: number, digits: number) =>
|
||||||
@@ -31,8 +32,9 @@ export function CategoryBreakdownListItem({
|
|||||||
category,
|
category,
|
||||||
periodParam,
|
periodParam,
|
||||||
config,
|
config,
|
||||||
|
position,
|
||||||
}: CategoryBreakdownListItemProps) {
|
}: CategoryBreakdownListItemProps) {
|
||||||
const hasBudget = category.budgetAmount !== null;
|
const hasBudget = config.showBudget && category.budgetAmount !== null;
|
||||||
const budgetExceeded =
|
const budgetExceeded =
|
||||||
hasBudget &&
|
hasBudget &&
|
||||||
category.budgetUsedPercentage !== null &&
|
category.budgetUsedPercentage !== null &&
|
||||||
@@ -44,26 +46,23 @@ export function CategoryBreakdownListItem({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<div className="flex items-center justify-between gap-3 transition-all duration-300 py-2">
|
<div className={styles.row}>
|
||||||
<div className="flex min-w-0 flex-1 items-center gap-2">
|
<span className={styles.rank}>{position}</span>
|
||||||
|
<div className={styles.main}>
|
||||||
<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:underline"
|
className={styles.titleLink}
|
||||||
>
|
>
|
||||||
<span className="truncate">{category.categoryName}</span>
|
<span className="truncate">{category.categoryName}</span>
|
||||||
<RiExternalLinkLine
|
|
||||||
className="size-3 shrink-0 text-muted-foreground"
|
|
||||||
aria-hidden
|
|
||||||
/>
|
|
||||||
</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,
|
||||||
@@ -71,15 +70,14 @@ export function CategoryBreakdownListItem({
|
|||||||
)}{" "}
|
)}{" "}
|
||||||
da {config.shareLabel}
|
da {config.shareLabel}
|
||||||
</span>
|
</span>
|
||||||
|
</div>
|
||||||
{hasBudget && category.budgetUsedPercentage !== null ? (
|
{hasBudget && category.budgetUsedPercentage !== null ? (
|
||||||
<>
|
<div
|
||||||
<span aria-hidden>·</span>
|
className={`mt-0.5 text-xs ${budgetExceeded ? "text-destructive" : "text-info"}`}
|
||||||
<span
|
|
||||||
className={`flex items-center gap-1 ${budgetExceeded ? "text-destructive" : "text-info"}`}
|
|
||||||
>
|
>
|
||||||
{budgetExceeded ? (
|
{budgetExceeded ? (
|
||||||
<>
|
<>
|
||||||
Excedeu{" "}
|
Limite excedido em{" "}
|
||||||
<span className="font-medium">
|
<span className="font-medium">
|
||||||
{formatCurrency(exceededAmount)}
|
{formatCurrency(exceededAmount)}
|
||||||
</span>
|
</span>
|
||||||
@@ -90,37 +88,32 @@ export function CategoryBreakdownListItem({
|
|||||||
category.budgetUsedPercentage,
|
category.budgetUsedPercentage,
|
||||||
config.percentageDigits,
|
config.percentageDigits,
|
||||||
)}{" "}
|
)}{" "}
|
||||||
do limite
|
do limite utilizado
|
||||||
{config.includeBudgetAmount &&
|
|
||||||
category.budgetAmount !== null
|
|
||||||
? ` ${formatCurrency(category.budgetAmount)}`
|
|
||||||
: ""}
|
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</span>
|
</div>
|
||||||
</>
|
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</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>
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ type CategoryBreakdownListConfig = {
|
|||||||
shareLabel: string;
|
shareLabel: string;
|
||||||
percentageDigits: number;
|
percentageDigits: number;
|
||||||
positiveTrend: "up" | "down";
|
positiveTrend: "up" | "down";
|
||||||
includeBudgetAmount: boolean;
|
showBudget: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
type CategoryBreakdownListProps = {
|
type CategoryBreakdownListProps = {
|
||||||
@@ -20,13 +20,14 @@ export function CategoryBreakdownList({
|
|||||||
config,
|
config,
|
||||||
}: CategoryBreakdownListProps) {
|
}: CategoryBreakdownListProps) {
|
||||||
return (
|
return (
|
||||||
<div>
|
<div className="flex flex-col">
|
||||||
{categories.map((category) => (
|
{categories.map((category, index) => (
|
||||||
<CategoryBreakdownListItem
|
<CategoryBreakdownListItem
|
||||||
key={category.categoryId}
|
key={category.categoryId}
|
||||||
category={category}
|
category={category}
|
||||||
periodParam={periodParam}
|
periodParam={periodParam}
|
||||||
config={config}
|
config={config}
|
||||||
|
position={index + 1}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -34,7 +34,7 @@ const VARIANT_CONFIG = {
|
|||||||
shareLabel: "receita total",
|
shareLabel: "receita total",
|
||||||
percentageDigits: 1,
|
percentageDigits: 1,
|
||||||
positiveTrend: "up",
|
positiveTrend: "up",
|
||||||
includeBudgetAmount: true,
|
showBudget: false,
|
||||||
},
|
},
|
||||||
expense: {
|
expense: {
|
||||||
emptyTitle: "Nenhuma despesa encontrada",
|
emptyTitle: "Nenhuma despesa encontrada",
|
||||||
@@ -43,7 +43,7 @@ const VARIANT_CONFIG = {
|
|||||||
shareLabel: "despesa total",
|
shareLabel: "despesa total",
|
||||||
percentageDigits: 0,
|
percentageDigits: 0,
|
||||||
positiveTrend: "down",
|
positiveTrend: "down",
|
||||||
includeBudgetAmount: false,
|
showBudget: true,
|
||||||
},
|
},
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ import {
|
|||||||
RiCloseLine,
|
RiCloseLine,
|
||||||
RiDragMove2Line,
|
RiDragMove2Line,
|
||||||
RiEyeOffLine,
|
RiEyeOffLine,
|
||||||
|
RiSettings4Line,
|
||||||
RiTodoLine,
|
RiTodoLine,
|
||||||
} from "@remixicon/react";
|
} from "@remixicon/react";
|
||||||
import { useMemo, useState, useTransition } from "react";
|
import { useMemo, useState, useTransition } from "react";
|
||||||
@@ -41,6 +42,12 @@ import {
|
|||||||
import { NoteDialog } from "@/features/notes/components/note-dialog";
|
import { NoteDialog } from "@/features/notes/components/note-dialog";
|
||||||
import { TransactionDialog } from "@/features/transactions/components/dialogs/transaction-dialog/transaction-dialog";
|
import { TransactionDialog } from "@/features/transactions/components/dialogs/transaction-dialog/transaction-dialog";
|
||||||
import { Button } from "@/shared/components/ui/button";
|
import { Button } from "@/shared/components/ui/button";
|
||||||
|
import {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
} from "@/shared/components/ui/dropdown-menu";
|
||||||
import { ExpandableWidgetCard } from "@/shared/components/widgets/expandable-widget-card";
|
import { ExpandableWidgetCard } from "@/shared/components/widgets/expandable-widget-card";
|
||||||
|
|
||||||
type DashboardGridEditableProps = {
|
type DashboardGridEditableProps = {
|
||||||
@@ -60,6 +67,9 @@ export function DashboardGridEditable({
|
|||||||
}: DashboardGridEditableProps) {
|
}: DashboardGridEditableProps) {
|
||||||
const [isEditing, setIsEditing] = useState(false);
|
const [isEditing, setIsEditing] = useState(false);
|
||||||
const [isPending, startTransition] = useTransition();
|
const [isPending, startTransition] = useTransition();
|
||||||
|
const [isMobileIncomeOpen, setIsMobileIncomeOpen] = useState(false);
|
||||||
|
const [isMobileExpenseOpen, setIsMobileExpenseOpen] = useState(false);
|
||||||
|
const [isMobileNoteOpen, setIsMobileNoteOpen] = useState(false);
|
||||||
|
|
||||||
// Initialize widget order and hidden state
|
// Initialize widget order and hidden state
|
||||||
const [widgetOrder, setWidgetOrder] = useState<string[]>(
|
const [widgetOrder, setWidgetOrder] = useState<string[]>(
|
||||||
@@ -132,14 +142,6 @@ export function DashboardGridEditable({
|
|||||||
: [...hiddenWidgets, widgetId];
|
: [...hiddenWidgets, widgetId];
|
||||||
|
|
||||||
setHiddenWidgets(newHidden);
|
setHiddenWidgets(newHidden);
|
||||||
|
|
||||||
// Salvar automaticamente ao toggle
|
|
||||||
startTransition(async () => {
|
|
||||||
await updateWidgetPreferences({
|
|
||||||
order: widgetOrder,
|
|
||||||
hidden: newHidden,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleHideWidget = (widgetId: string) => {
|
const handleHideWidget = (widgetId: string) => {
|
||||||
@@ -182,6 +184,8 @@ export function DashboardGridEditable({
|
|||||||
setWidgetOrder(DEFAULT_WIDGET_ORDER);
|
setWidgetOrder(DEFAULT_WIDGET_ORDER);
|
||||||
setHiddenWidgets([]);
|
setHiddenWidgets([]);
|
||||||
setMyAccountsShowExcluded(true);
|
setMyAccountsShowExcluded(true);
|
||||||
|
setOriginalOrder(DEFAULT_WIDGET_ORDER);
|
||||||
|
setOriginalHidden([]);
|
||||||
toast.success("Preferências restauradas!");
|
toast.success("Preferências restauradas!");
|
||||||
} else {
|
} else {
|
||||||
toast.error(result.error ?? "Erro ao restaurar");
|
toast.error(result.error ?? "Erro ao restaurar");
|
||||||
@@ -195,7 +199,68 @@ export function DashboardGridEditable({
|
|||||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||||
{!isEditing ? (
|
{!isEditing ? (
|
||||||
<div className="flex w-full min-w-0 flex-col gap-1 sm:w-auto sm:flex-row sm:items-center sm:gap-2">
|
<div className="flex w-full min-w-0 flex-col gap-1 sm:w-auto sm:flex-row sm:items-center sm:gap-2">
|
||||||
<div className="-mb-1 grid w-full grid-cols-3 gap-1 pb-1 sm:mb-0 sm:flex sm:w-auto sm:items-center sm:gap-2 sm:overflow-visible sm:pb-0">
|
<div className="sm:hidden">
|
||||||
|
<DropdownMenu>
|
||||||
|
<DropdownMenuTrigger asChild>
|
||||||
|
<Button size="sm" variant="outline" className="w-full gap-2">
|
||||||
|
<RiAddFill className="size-4 text-primary" />
|
||||||
|
Adicionar
|
||||||
|
</Button>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent align="start" className="w-48">
|
||||||
|
<DropdownMenuItem
|
||||||
|
onSelect={() => setIsMobileIncomeOpen(true)}
|
||||||
|
>
|
||||||
|
<RiAddFill className="text-success/80" />
|
||||||
|
Nova receita
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem
|
||||||
|
onSelect={() => setIsMobileExpenseOpen(true)}
|
||||||
|
>
|
||||||
|
<RiAddFill className="text-destructive/80" />
|
||||||
|
Nova despesa
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem onSelect={() => setIsMobileNoteOpen(true)}>
|
||||||
|
<RiTodoLine className="text-info/80" />
|
||||||
|
Nova anotação
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
<TransactionDialog
|
||||||
|
mode="create"
|
||||||
|
open={isMobileIncomeOpen}
|
||||||
|
onOpenChange={setIsMobileIncomeOpen}
|
||||||
|
payerOptions={quickActionOptions.payerOptions}
|
||||||
|
splitPayerOptions={quickActionOptions.splitPayerOptions}
|
||||||
|
defaultPayerId={quickActionOptions.defaultPayerId}
|
||||||
|
accountOptions={quickActionOptions.accountOptions}
|
||||||
|
cardOptions={quickActionOptions.cardOptions}
|
||||||
|
categoryOptions={quickActionOptions.categoryOptions}
|
||||||
|
estabelecimentos={quickActionOptions.estabelecimentos}
|
||||||
|
defaultPeriod={period}
|
||||||
|
defaultTransactionType="Receita"
|
||||||
|
/>
|
||||||
|
<TransactionDialog
|
||||||
|
mode="create"
|
||||||
|
open={isMobileExpenseOpen}
|
||||||
|
onOpenChange={setIsMobileExpenseOpen}
|
||||||
|
payerOptions={quickActionOptions.payerOptions}
|
||||||
|
splitPayerOptions={quickActionOptions.splitPayerOptions}
|
||||||
|
defaultPayerId={quickActionOptions.defaultPayerId}
|
||||||
|
accountOptions={quickActionOptions.accountOptions}
|
||||||
|
cardOptions={quickActionOptions.cardOptions}
|
||||||
|
categoryOptions={quickActionOptions.categoryOptions}
|
||||||
|
estabelecimentos={quickActionOptions.estabelecimentos}
|
||||||
|
defaultPeriod={period}
|
||||||
|
defaultTransactionType="Despesa"
|
||||||
|
/>
|
||||||
|
<NoteDialog
|
||||||
|
mode="create"
|
||||||
|
open={isMobileNoteOpen}
|
||||||
|
onOpenChange={setIsMobileNoteOpen}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="hidden items-center gap-2 sm:flex">
|
||||||
<TransactionDialog
|
<TransactionDialog
|
||||||
mode="create"
|
mode="create"
|
||||||
payerOptions={quickActionOptions.payerOptions}
|
payerOptions={quickActionOptions.payerOptions}
|
||||||
@@ -269,6 +334,12 @@ export function DashboardGridEditable({
|
|||||||
<div className="flex w-full items-center justify-end gap-2 sm:w-auto">
|
<div className="flex w-full items-center justify-end gap-2 sm:w-auto">
|
||||||
{isEditing ? (
|
{isEditing ? (
|
||||||
<>
|
<>
|
||||||
|
<WidgetSettingsDialog
|
||||||
|
hiddenWidgets={hiddenWidgets}
|
||||||
|
onToggleWidget={handleToggleWidget}
|
||||||
|
onReset={handleReset}
|
||||||
|
triggerLabel="Visibilidade"
|
||||||
|
/>
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
size="sm"
|
size="sm"
|
||||||
@@ -290,21 +361,15 @@ export function DashboardGridEditable({
|
|||||||
</Button>
|
</Button>
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<div className="grid w-full grid-cols-2 gap-2 sm:flex sm:w-auto">
|
<div className="w-full sm:w-auto">
|
||||||
<WidgetSettingsDialog
|
|
||||||
hiddenWidgets={hiddenWidgets}
|
|
||||||
onToggleWidget={handleToggleWidget}
|
|
||||||
onReset={handleReset}
|
|
||||||
triggerClassName="w-full sm:w-auto"
|
|
||||||
/>
|
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
size="sm"
|
size="sm"
|
||||||
onClick={handleStartEditing}
|
onClick={handleStartEditing}
|
||||||
className="w-full gap-2 sm:w-auto"
|
className="w-full gap-2 sm:w-auto"
|
||||||
>
|
>
|
||||||
<RiDragMove2Line className="size-4" />
|
<RiSettings4Line className="size-4" />
|
||||||
Reordenar
|
Personalizar
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
import {
|
import {
|
||||||
RiArrowLeftRightLine,
|
RiArrowLeftRightLine,
|
||||||
RiArrowRightDownLine,
|
RiArrowRightDownLine,
|
||||||
|
RiArrowRightLine,
|
||||||
RiArrowRightUpLine,
|
RiArrowRightUpLine,
|
||||||
RiCalendar2Line,
|
RiCalendar2Line,
|
||||||
} from "@remixicon/react";
|
} from "@remixicon/react";
|
||||||
|
import Link from "next/link";
|
||||||
import { MetricsCardInfoButton } from "@/features/dashboard/components/metrics-card-info-button";
|
import { MetricsCardInfoButton } from "@/features/dashboard/components/metrics-card-info-button";
|
||||||
import { PercentageChangeIndicator } from "@/features/dashboard/components/percentage-change-indicator";
|
import { PercentageChangeIndicator } from "@/features/dashboard/components/percentage-change-indicator";
|
||||||
import type { DashboardCardMetrics } from "@/features/dashboard/overview/dashboard-metrics-queries";
|
import type { DashboardCardMetrics } from "@/features/dashboard/overview/dashboard-metrics-queries";
|
||||||
@@ -18,10 +20,13 @@ import {
|
|||||||
} from "@/shared/components/ui/card";
|
} from "@/shared/components/ui/card";
|
||||||
import { Separator } from "@/shared/components/ui/separator";
|
import { Separator } from "@/shared/components/ui/separator";
|
||||||
import { formatPercentage } from "@/shared/utils/percentage";
|
import { formatPercentage } from "@/shared/utils/percentage";
|
||||||
|
import { formatPeriodForUrl } from "@/shared/utils/period";
|
||||||
import { cn } from "@/shared/utils/ui";
|
import { cn } from "@/shared/utils/ui";
|
||||||
|
|
||||||
type DashboardMetricsCardsProps = {
|
type DashboardMetricsCardsProps = {
|
||||||
metrics: DashboardCardMetrics;
|
metrics: DashboardCardMetrics;
|
||||||
|
period: string;
|
||||||
|
adminPayerSlug: string | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
type Trend = "up" | "down" | "flat";
|
type Trend = "up" | "down" | "flat";
|
||||||
@@ -36,6 +41,7 @@ const CARDS = [
|
|||||||
icon: RiArrowRightDownLine,
|
icon: RiArrowRightDownLine,
|
||||||
invertTrend: false,
|
invertTrend: false,
|
||||||
iconClass: "text-success",
|
iconClass: "text-success",
|
||||||
|
transactionType: "receita",
|
||||||
helpTitle: "Como calculamos receitas",
|
helpTitle: "Como calculamos receitas",
|
||||||
helpLines: [
|
helpLines: [
|
||||||
"Somamos os lançamentos do tipo Receita no período selecionado.",
|
"Somamos os lançamentos do tipo Receita no período selecionado.",
|
||||||
@@ -53,6 +59,7 @@ const CARDS = [
|
|||||||
icon: RiArrowRightUpLine,
|
icon: RiArrowRightUpLine,
|
||||||
invertTrend: true,
|
invertTrend: true,
|
||||||
iconClass: "text-destructive",
|
iconClass: "text-destructive",
|
||||||
|
transactionType: "despesa",
|
||||||
helpTitle: "Como calculamos despesas",
|
helpTitle: "Como calculamos despesas",
|
||||||
helpLines: [
|
helpLines: [
|
||||||
"Somamos os lançamentos do tipo Despesa no período selecionado.",
|
"Somamos os lançamentos do tipo Despesa no período selecionado.",
|
||||||
@@ -70,6 +77,7 @@ const CARDS = [
|
|||||||
icon: RiArrowLeftRightLine,
|
icon: RiArrowLeftRightLine,
|
||||||
invertTrend: false,
|
invertTrend: false,
|
||||||
iconClass: "text-warning",
|
iconClass: "text-warning",
|
||||||
|
transactionType: null,
|
||||||
helpTitle: "Como calculamos o balanço",
|
helpTitle: "Como calculamos o balanço",
|
||||||
helpLines: [
|
helpLines: [
|
||||||
"Partimos de receitas menos despesas do período.",
|
"Partimos de receitas menos despesas do período.",
|
||||||
@@ -86,6 +94,7 @@ const CARDS = [
|
|||||||
icon: RiCalendar2Line,
|
icon: RiCalendar2Line,
|
||||||
invertTrend: false,
|
invertTrend: false,
|
||||||
iconClass: "text-cyan-600",
|
iconClass: "text-cyan-600",
|
||||||
|
transactionType: null,
|
||||||
helpTitle: "Como calculamos o previsto",
|
helpTitle: "Como calculamos o previsto",
|
||||||
helpLines: [
|
helpLines: [
|
||||||
"Acumulamos o balanço mês a mês até o período atual.",
|
"Acumulamos o balanço mês a mês até o período atual.",
|
||||||
@@ -123,7 +132,11 @@ const getPercentChange = (current: number, previous: number): string | null => {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
export function DashboardMetricsCards({ metrics }: DashboardMetricsCardsProps) {
|
export function DashboardMetricsCards({
|
||||||
|
metrics,
|
||||||
|
period,
|
||||||
|
adminPayerSlug,
|
||||||
|
}: DashboardMetricsCardsProps) {
|
||||||
return (
|
return (
|
||||||
<div className="grid grid-cols-1 gap-3 @xl/main:grid-cols-2 @5xl/main:grid-cols-4">
|
<div className="grid grid-cols-1 gap-3 @xl/main:grid-cols-2 @5xl/main:grid-cols-4">
|
||||||
{CARDS.map(
|
{CARDS.map(
|
||||||
@@ -134,6 +147,7 @@ export function DashboardMetricsCards({ metrics }: DashboardMetricsCardsProps) {
|
|||||||
icon: Icon,
|
icon: Icon,
|
||||||
invertTrend,
|
invertTrend,
|
||||||
iconClass,
|
iconClass,
|
||||||
|
transactionType,
|
||||||
helpTitle,
|
helpTitle,
|
||||||
helpLines,
|
helpLines,
|
||||||
}) => {
|
}) => {
|
||||||
@@ -143,10 +157,14 @@ export function DashboardMetricsCards({ metrics }: DashboardMetricsCardsProps) {
|
|||||||
metric.current,
|
metric.current,
|
||||||
metric.previous,
|
metric.previous,
|
||||||
);
|
);
|
||||||
|
const transactionsHref = transactionType
|
||||||
|
? `/transactions?periodo=${formatPeriodForUrl(period)}&type=${transactionType}${adminPayerSlug ? `&payer=${adminPayerSlug}` : ""}`
|
||||||
|
: null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card key={label} className="gap-2 overflow-hidden">
|
<Card key={label} className="gap-2 overflow-hidden py-6">
|
||||||
<CardHeader className="gap-1">
|
<CardHeader className="gap-1">
|
||||||
|
<div className="flex items-center justify-between gap-2">
|
||||||
<CardTitle className="flex items-center gap-1">
|
<CardTitle className="flex items-center gap-1">
|
||||||
<Icon className={cn("size-4", iconClass)} aria-hidden />
|
<Icon className={cn("size-4", iconClass)} aria-hidden />
|
||||||
{label}
|
{label}
|
||||||
@@ -156,6 +174,16 @@ export function DashboardMetricsCards({ metrics }: DashboardMetricsCardsProps) {
|
|||||||
helpLines={helpLines}
|
helpLines={helpLines}
|
||||||
/>
|
/>
|
||||||
</CardTitle>
|
</CardTitle>
|
||||||
|
{transactionsHref ? (
|
||||||
|
<Link
|
||||||
|
href={transactionsHref}
|
||||||
|
className="rounded-sm px-1 text-muted-foreground/60 transition-colors hover:bg-accent hover:text-primary focus-visible:outline-none focus-visible:ring-ring/50 focus-visible:ring-[3px]"
|
||||||
|
aria-label={`Ver lançamentos de ${label.toLowerCase()}`}
|
||||||
|
>
|
||||||
|
<RiArrowRightLine className="size-4" aria-hidden />
|
||||||
|
</Link>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
<CardDescription className="mt-1 tracking-tight">
|
<CardDescription className="mt-1 tracking-tight">
|
||||||
{subtitle}
|
{subtitle}
|
||||||
</CardDescription>
|
</CardDescription>
|
||||||
|
|||||||
@@ -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 { PercentageChangeIndicator } from "@/features/dashboard/components/percentage-change-indicator";
|
import Link from "next/link";
|
||||||
|
import { dashboardWidgetListStyles as styles } from "@/features/dashboard/components/dashboard-widget-list-styles";
|
||||||
import {
|
import {
|
||||||
clampGoalProgress,
|
clampGoalProgress,
|
||||||
formatGoalProgressPercentage,
|
formatGoalProgressPercentage,
|
||||||
@@ -9,24 +10,28 @@ import { CategoryIconBadge } 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";
|
||||||
import { Progress } from "@/shared/components/ui/progress";
|
import { Progress } from "@/shared/components/ui/progress";
|
||||||
|
import {
|
||||||
|
Tooltip,
|
||||||
|
TooltipContent,
|
||||||
|
TooltipTrigger,
|
||||||
|
} from "@/shared/components/ui/tooltip";
|
||||||
|
import { cn } from "@/shared/utils";
|
||||||
|
import { formatPeriodForUrl } from "@/shared/utils/period";
|
||||||
|
|
||||||
type GoalProgressItemProps = {
|
type GoalProgressItemProps = {
|
||||||
item: GoalProgressItemData;
|
item: GoalProgressItemData;
|
||||||
index: number;
|
|
||||||
onEdit: (item: GoalProgressItemData) => void;
|
onEdit: (item: GoalProgressItemData) => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function GoalProgressItem({
|
export function GoalProgressItem({ item, onEdit }: GoalProgressItemProps) {
|
||||||
item,
|
|
||||||
index,
|
|
||||||
onEdit,
|
|
||||||
}: GoalProgressItemProps) {
|
|
||||||
const progressValue = clampGoalProgress(item.usedPercentage, 0, 100);
|
const progressValue = clampGoalProgress(item.usedPercentage, 0, 100);
|
||||||
const percentageDelta = item.usedPercentage - 100;
|
|
||||||
const isExceeded = item.status === "exceeded";
|
const isExceeded = item.status === "exceeded";
|
||||||
|
const isCritical = item.status === "critical";
|
||||||
|
const exceededAmount = Math.max(item.spentAmount - item.budgetAmount, 0);
|
||||||
|
const usedPercentageLabel = formatGoalProgressPercentage(item.usedPercentage);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="group transition-all duration-300 py-2">
|
<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
|
||||||
@@ -35,46 +40,70 @@ export function GoalProgressItem({
|
|||||||
size="md"
|
size="md"
|
||||||
/>
|
/>
|
||||||
<div className="min-w-0 flex-1">
|
<div className="min-w-0 flex-1">
|
||||||
<p className="truncate text-sm font-medium text-foreground">
|
{item.categoryId ? (
|
||||||
|
<Link
|
||||||
|
href={`/categories/${item.categoryId}?periodo=${formatPeriodForUrl(item.period)}`}
|
||||||
|
className={`${styles.title} block underline-offset-2 hover:text-primary hover:underline`}
|
||||||
|
>
|
||||||
{item.categoryName}
|
{item.categoryName}
|
||||||
</p>
|
</Link>
|
||||||
<p className="mt-0.5 text-xs text-muted-foreground">
|
) : (
|
||||||
|
<p className={styles.title}>{item.categoryName}</p>
|
||||||
|
)}
|
||||||
|
<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} />
|
||||||
<PercentageChangeIndicator
|
<span aria-hidden> · </span>
|
||||||
value={percentageDelta}
|
<span
|
||||||
label={formatGoalProgressPercentage(percentageDelta, true)}
|
className={cn(
|
||||||
positiveTrend="down"
|
"font-medium",
|
||||||
className="ml-1.5 align-middle"
|
isExceeded && "text-destructive",
|
||||||
/>
|
isCritical && "text-warning",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{isExceeded ? (
|
||||||
|
<>
|
||||||
|
<MoneyValues amount={exceededAmount} /> acima do limite
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
`${usedPercentageLabel} utilizado`
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex shrink-0 items-center gap-2">
|
<Tooltip>
|
||||||
|
<TooltipTrigger asChild>
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
variant="link"
|
variant="ghost"
|
||||||
size="icon-sm"
|
size="icon-sm"
|
||||||
className="transition-opacity text-primary hover:opacity-80"
|
className="shrink-0 text-primary/70 opacity-70 transition-all hover:text-primary hover:opacity-100 focus-visible:text-primary focus-visible:opacity-100 group-hover:opacity-100 group-focus-within:opacity-100"
|
||||||
onClick={() => onEdit(item)}
|
onClick={() => onEdit(item)}
|
||||||
aria-label={`Atualizar orçamento de ${item.categoryName}`}
|
aria-label={`Atualizar orçamento de ${item.categoryName}`}
|
||||||
>
|
>
|
||||||
<RiPencilLine className="size-3.5" />
|
<RiPencilLine className="size-3.5" />
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</TooltipTrigger>
|
||||||
|
<TooltipContent side="top">Atualizar orçamento</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
</div>
|
</div>
|
||||||
<div className="ml-11 mt-1.5">
|
<div className="ml-11 mt-1.5">
|
||||||
<Progress
|
<Progress
|
||||||
value={progressValue}
|
value={progressValue}
|
||||||
className={
|
className={cn(
|
||||||
isExceeded
|
isExceeded && "bg-destructive/20",
|
||||||
? "**:data-[slot=progress-indicator]:bg-destructive bg-destructive/20"
|
isCritical && "bg-warning/20",
|
||||||
: undefined
|
)}
|
||||||
}
|
indicatorClassName={cn(
|
||||||
|
isExceeded && "bg-destructive",
|
||||||
|
isCritical && "bg-warning",
|
||||||
|
)}
|
||||||
|
aria-label={`${usedPercentageLabel} do orçamento utilizado em ${item.categoryName}`}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</li>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,13 +21,8 @@ export function GoalsProgressList({ items, onEdit }: GoalsProgressListProps) {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<ul className="flex flex-col">
|
<ul className="flex flex-col">
|
||||||
{items.map((item, index) => (
|
{items.map((item) => (
|
||||||
<GoalProgressListItem
|
<GoalProgressListItem key={item.id} item={item} onEdit={onEdit} />
|
||||||
key={item.id}
|
|
||||||
item={item}
|
|
||||||
index={index}
|
|
||||||
onEdit={onEdit}
|
|
||||||
/>
|
|
||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -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 ? (
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import {
|
|||||||
TooltipContent,
|
TooltipContent,
|
||||||
TooltipTrigger,
|
TooltipTrigger,
|
||||||
} from "@/shared/components/ui/tooltip";
|
} from "@/shared/components/ui/tooltip";
|
||||||
|
import { getPaymentMethodIcon } from "@/shared/utils/icons";
|
||||||
|
|
||||||
type InstallmentExpenseListItemProps = {
|
type InstallmentExpenseListItemProps = {
|
||||||
expense: InstallmentExpense;
|
expense: InstallmentExpense;
|
||||||
@@ -28,7 +29,7 @@ export function InstallmentExpenseListItem({
|
|||||||
} = buildInstallmentExpenseDisplay(expense);
|
} = buildInstallmentExpenseDisplay(expense);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center gap-3 transition-all duration-300 py-2">
|
<div 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="min-w-0 flex-1">
|
||||||
@@ -66,22 +67,32 @@ export function InstallmentExpenseListItem({
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between gap-2 text-xs text-muted-foreground">
|
||||||
|
<span className="inline-flex min-w-0 items-center gap-1">
|
||||||
|
<span
|
||||||
|
className="inline-flex shrink-0 [&_svg]:size-3.5"
|
||||||
|
title={expense.paymentMethod}
|
||||||
|
>
|
||||||
|
{getPaymentMethodIcon(expense.paymentMethod)}
|
||||||
|
<span className="sr-only">{expense.paymentMethod}</span>
|
||||||
|
</span>
|
||||||
|
{endDate ? <span className="shrink-0">Até {endDate}</span> : null}
|
||||||
|
</span>
|
||||||
|
<span className="shrink-0">
|
||||||
{remainingInstallments === 0 ? (
|
{remainingInstallments === 0 ? (
|
||||||
<p className="text-xs text-muted-foreground">
|
"Quitado"
|
||||||
{endDate ? `Termina em ${endDate}` : null}
|
|
||||||
{" · Quitado"}
|
|
||||||
</p>
|
|
||||||
) : (
|
) : (
|
||||||
<p className="text-xs text-muted-foreground">
|
<>
|
||||||
{endDate ? `Termina em ${endDate}` : null}
|
{remainingLabel}:{" "}
|
||||||
{` · ${remainingLabel}: `}
|
|
||||||
<MoneyValues
|
<MoneyValues
|
||||||
amount={remainingAmount}
|
amount={remainingAmount}
|
||||||
className="inline-block font-semibold"
|
className="inline-block font-semibold"
|
||||||
/>{" "}
|
/>{" "}
|
||||||
({remainingInstallments}x)
|
({remainingInstallments}x)
|
||||||
</p>
|
</>
|
||||||
)}
|
)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
<Progress value={progress} className="mt-1 h-2" />
|
<Progress value={progress} className="mt-1 h-2" />
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -14,17 +14,17 @@ export function InstallmentExpensesList({
|
|||||||
return (
|
return (
|
||||||
<WidgetEmptyState
|
<WidgetEmptyState
|
||||||
icon={<RiNumbersLine className="size-6 text-muted-foreground" />}
|
icon={<RiNumbersLine className="size-6 text-muted-foreground" />}
|
||||||
title="Nenhuma despesa parcelada"
|
title="Nenhuma despesa parcelada encontrada"
|
||||||
description="Lançamentos parcelados aparecerão aqui conforme forem registrados."
|
description="Lançamentos parcelados aparecerão aqui conforme forem registrados."
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ul className="flex flex-col">
|
<div className="flex flex-col">
|
||||||
{expenses.map((expense) => (
|
{expenses.map((expense) => (
|
||||||
<InstallmentExpenseListItem key={expense.id} expense={expense} />
|
<InstallmentExpenseListItem key={expense.id} expense={expense} />
|
||||||
))}
|
))}
|
||||||
</ul>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
import { RiCheckboxCircleFill, RiExternalLinkLine } 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,
|
||||||
buildInvoiceInitials,
|
buildInvoiceInitials,
|
||||||
formatInvoicePaymentDate,
|
formatInvoicePaymentDate,
|
||||||
|
formatInvoiceWidgetOverdueLabel,
|
||||||
formatInvoiceWidgetPaymentDate,
|
formatInvoiceWidgetPaymentDate,
|
||||||
getInvoiceShareLabel,
|
getInvoiceShareLabel,
|
||||||
parseInvoiceDueDate,
|
parseInvoiceDueDate,
|
||||||
@@ -48,31 +50,27 @@ export function InvoiceListItem({ invoice, onPay }: InvoiceListItemProps) {
|
|||||||
const absolutePaymentInfo = formatInvoicePaymentDate(invoice.paidAt);
|
const absolutePaymentInfo = formatInvoicePaymentDate(invoice.paidAt);
|
||||||
const breakdown = invoice.pagadorBreakdown ?? [];
|
const breakdown = invoice.pagadorBreakdown ?? [];
|
||||||
const hasBreakdown = breakdown.length > 0;
|
const hasBreakdown = breakdown.length > 0;
|
||||||
|
const hasMultiplePayers = breakdown.length > 1;
|
||||||
const detailHref = buildInvoiceDetailsHref(invoice.cardId, invoice.period);
|
const detailHref = buildInvoiceDetailsHref(invoice.cardId, invoice.period);
|
||||||
|
const overdueLabel = formatInvoiceWidgetOverdueLabel(dueInfo.date);
|
||||||
const dueTooltipLabel =
|
const dueTooltipLabel =
|
||||||
dueInfo.label !== absoluteDueInfo.label ? absoluteDueInfo.label : null;
|
overdueLabel || dueInfo.label !== absoluteDueInfo.label
|
||||||
|
? absoluteDueInfo.label
|
||||||
|
: null;
|
||||||
const paymentTooltipLabel =
|
const paymentTooltipLabel =
|
||||||
paymentInfo?.label && paymentInfo.label !== absolutePaymentInfo?.label
|
paymentInfo?.label && paymentInfo.label !== absolutePaymentInfo?.label
|
||||||
? absolutePaymentInfo?.label
|
? absolutePaymentInfo?.label
|
||||||
: 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>
|
||||||
<RiExternalLinkLine
|
|
||||||
className="size-3 shrink-0 text-muted-foreground"
|
|
||||||
aria-hidden
|
|
||||||
/>
|
|
||||||
</Link>
|
</Link>
|
||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div 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}
|
||||||
@@ -80,7 +78,8 @@ 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">
|
||||||
{hasBreakdown ? (
|
{hasBreakdown ? (
|
||||||
<HoverCard openDelay={150}>
|
<HoverCard openDelay={150}>
|
||||||
<HoverCardTrigger asChild>{linkNode}</HoverCardTrigger>
|
<HoverCardTrigger asChild>{linkNode}</HoverCardTrigger>
|
||||||
@@ -121,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>
|
||||||
))}
|
))}
|
||||||
@@ -133,18 +137,46 @@ export function InvoiceListItem({ invoice, onPay }: InvoiceListItemProps) {
|
|||||||
) : (
|
) : (
|
||||||
linkNode
|
linkNode
|
||||||
)}
|
)}
|
||||||
|
{hasMultiplePayers ? (
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger asChild>
|
||||||
|
<span className="inline-flex shrink-0 cursor-help text-muted-foreground">
|
||||||
|
<RiGroupLine className="size-3.5" aria-hidden />
|
||||||
|
<span className="sr-only">Ver distribuição por pessoa</span>
|
||||||
|
</span>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent side="top">
|
||||||
|
Ver distribuição por pessoa
|
||||||
|
</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
) : null}
|
||||||
|
</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>
|
||||||
<TooltipTrigger asChild>
|
<TooltipTrigger asChild>
|
||||||
<span className="cursor-help">{dueInfo.label}</span>
|
<span
|
||||||
|
className={
|
||||||
|
isOverdue
|
||||||
|
? "cursor-help font-semibold text-destructive"
|
||||||
|
: "cursor-help"
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{overdueLabel ?? dueInfo.label}
|
||||||
|
</span>
|
||||||
</TooltipTrigger>
|
</TooltipTrigger>
|
||||||
<TooltipContent side="top">{dueTooltipLabel}</TooltipContent>
|
<TooltipContent side="top">{dueTooltipLabel}</TooltipContent>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
) : (
|
) : (
|
||||||
<span>{dueInfo.label}</span>
|
<span
|
||||||
|
className={
|
||||||
|
isOverdue ? "font-semibold text-destructive" : undefined
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{overdueLabel ?? dueInfo.label}
|
||||||
|
</span>
|
||||||
)
|
)
|
||||||
) : null}
|
) : null}
|
||||||
{isPaid && paymentInfo ? (
|
{isPaid && paymentInfo ? (
|
||||||
@@ -169,24 +201,24 @@ 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 ? (
|
||||||
|
<span className={`${styles.trailingMeta} text-success`}>
|
||||||
|
<RiCheckboxCircleFill className="size-3.5" /> Pago
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
size="sm"
|
size="sm"
|
||||||
variant="link"
|
variant="link"
|
||||||
className="h-auto p-0 disabled:opacity-100"
|
className={styles.actionButton}
|
||||||
disabled={isPaid}
|
|
||||||
onClick={() => onPay(invoice.id)}
|
onClick={() => onPay(invoice.id)}
|
||||||
>
|
>
|
||||||
{isPaid ? (
|
{isOverdue ? (
|
||||||
<span className="flex items-center gap-0.5 text-success">
|
|
||||||
<RiCheckboxCircleFill className="size-3.5" /> Pago
|
|
||||||
</span>
|
|
||||||
) : isOverdue ? (
|
|
||||||
<span className="overdue-blink">
|
<span className="overdue-blink">
|
||||||
<span className="overdue-blink-primary text-destructive">
|
<span className="overdue-blink-primary text-destructive">
|
||||||
Atrasado
|
Atrasado
|
||||||
@@ -197,7 +229,8 @@ export function InvoiceListItem({ invoice, onPay }: InvoiceListItemProps) {
|
|||||||
<span>Pagar</span>
|
<span>Pagar</span>
|
||||||
)}
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</li>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -39,9 +39,7 @@ export function InvoicesWidgetView({
|
|||||||
}: InvoicesWidgetViewProps) {
|
}: InvoicesWidgetViewProps) {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="flex flex-col gap-4">
|
|
||||||
<InvoicesList invoices={invoices} onPay={onOpenPaymentDialog} />
|
<InvoicesList invoices={invoices} onPay={onOpenPaymentDialog} />
|
||||||
</div>
|
|
||||||
|
|
||||||
<InvoicePaymentDialog
|
<InvoicePaymentDialog
|
||||||
invoice={selectedInvoice}
|
invoice={selectedInvoice}
|
||||||
|
|||||||
@@ -1,4 +1,9 @@
|
|||||||
import { RiFileList2Line, RiPencilLine } from "@remixicon/react";
|
import {
|
||||||
|
RiCalendarLine,
|
||||||
|
RiFileList2Line,
|
||||||
|
RiPencilLine,
|
||||||
|
} 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,
|
||||||
@@ -7,6 +12,11 @@ import {
|
|||||||
} from "@/features/notes/lib/formatters";
|
} from "@/features/notes/lib/formatters";
|
||||||
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 {
|
||||||
|
Tooltip,
|
||||||
|
TooltipContent,
|
||||||
|
TooltipTrigger,
|
||||||
|
} from "@/shared/components/ui/tooltip";
|
||||||
|
|
||||||
type NoteListItemProps = {
|
type NoteListItemProps = {
|
||||||
note: Note;
|
note: Note;
|
||||||
@@ -21,43 +31,57 @@ export function NoteListItem({
|
|||||||
}: NoteListItemProps) {
|
}: NoteListItemProps) {
|
||||||
const displayTitle = buildNoteDisplayTitle(note.title);
|
const displayTitle = buildNoteDisplayTitle(note.title);
|
||||||
const createdAtLabel = formatNoteCreatedAt(note.createdAt);
|
const createdAtLabel = formatNoteCreatedAt(note.createdAt);
|
||||||
|
const isTask = note.type === "tarefa";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="group flex items-center justify-between gap-2 transition-all duration-300 py-2">
|
<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>
|
{isTask ? (
|
||||||
<div className="mt-1 flex items-center gap-2">
|
|
||||||
<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>
|
||||||
<p className="truncate text-xs text-muted-foreground">
|
) : null}
|
||||||
|
<p className="truncate">
|
||||||
|
<span className="inline-flex items-center gap-1">
|
||||||
|
<RiCalendarLine className="size-3.5 shrink-0" />
|
||||||
{createdAtLabel}
|
{createdAtLabel}
|
||||||
|
</span>
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex shrink-0 items-center">
|
<div className="flex min-w-[4.5rem] shrink-0 items-center justify-end gap-0.5">
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger asChild>
|
||||||
<Button
|
<Button
|
||||||
variant="link"
|
variant="ghost"
|
||||||
size="icon-sm"
|
size="icon-sm"
|
||||||
className="transition-opacity text-primary hover:opacity-80"
|
className="text-primary/70 opacity-70 transition-all hover:text-primary hover:opacity-100 focus-visible:text-primary focus-visible:opacity-100 group-hover:opacity-100 group-focus-within:opacity-100"
|
||||||
onClick={() => onOpenEdit(note)}
|
onClick={() => onOpenEdit(note)}
|
||||||
aria-label={`Editar anotação ${displayTitle}`}
|
aria-label={`Editar anotação ${displayTitle}`}
|
||||||
>
|
>
|
||||||
<RiPencilLine className="size-4" />
|
<RiPencilLine className="size-4" />
|
||||||
</Button>
|
</Button>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent side="top">Editar anotação</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger asChild>
|
||||||
<Button
|
<Button
|
||||||
variant="link"
|
variant="ghost"
|
||||||
size="icon-sm"
|
size="icon-sm"
|
||||||
className="transition-opacity text-primary hover:opacity-80"
|
className="text-primary/70 opacity-70 transition-all hover:text-primary hover:opacity-100 focus-visible:text-primary focus-visible:opacity-100 group-hover:opacity-100 group-focus-within:opacity-100"
|
||||||
onClick={() => onOpenDetails(note)}
|
onClick={() => onOpenDetails(note)}
|
||||||
aria-label={`Ver detalhes da anotação ${displayTitle}`}
|
aria-label={`Ver detalhes da anotação ${displayTitle}`}
|
||||||
>
|
>
|
||||||
<RiFileList2Line className="size-4" />
|
<RiFileList2Line className="size-4" />
|
||||||
</Button>
|
</Button>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent side="top">Ver detalhes</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</li>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ export function NotesWidgetView({
|
|||||||
}: NotesWidgetViewProps) {
|
}: NotesWidgetViewProps) {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="flex flex-col gap-4 px-0">
|
<div className="flex flex-col px-0">
|
||||||
<NotesList
|
<NotesList
|
||||||
notes={notes}
|
notes={notes}
|
||||||
onOpenEdit={onOpenEdit}
|
onOpenEdit={onOpenEdit}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { RiExternalLinkLine } from "@remixicon/react";
|
|
||||||
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,
|
||||||
@@ -24,13 +24,16 @@ export type PaymentBreakdownListItemData = {
|
|||||||
|
|
||||||
type PaymentBreakdownListItemProps = {
|
type PaymentBreakdownListItemProps = {
|
||||||
item: PaymentBreakdownListItemData;
|
item: PaymentBreakdownListItemData;
|
||||||
|
position: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function PaymentBreakdownListItem({
|
export function PaymentBreakdownListItem({
|
||||||
item,
|
item,
|
||||||
|
position,
|
||||||
}: PaymentBreakdownListItemProps) {
|
}: PaymentBreakdownListItemProps) {
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center gap-3 transition-all duration-300 py-1.5">
|
<div className={styles.row}>
|
||||||
|
<span className={styles.rank}>{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={{
|
||||||
@@ -41,30 +44,28 @@ 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>
|
||||||
<RiExternalLinkLine
|
|
||||||
className="size-3 shrink-0 text-muted-foreground"
|
|
||||||
aria-hidden
|
|
||||||
/>
|
|
||||||
</Link>
|
</Link>
|
||||||
) : (
|
) : (
|
||||||
<p className="text-sm font-medium text-foreground">{item.title}</p>
|
<p className={styles.title}>{item.title}</p>
|
||||||
)}
|
)}
|
||||||
<MoneyValues className="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>{formatPaymentBreakdownPercentage(item.percentage)}</span>
|
<span className="ml-auto">
|
||||||
|
{formatPaymentBreakdownPercentage(item.percentage)} do total
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="mt-1">
|
<div className="mt-1">
|
||||||
|
|||||||
@@ -31,10 +31,14 @@ export function PaymentBreakdownList({
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-4 px-0">
|
<div className="flex flex-col px-0">
|
||||||
<ul className="flex flex-col gap-2">
|
<ul className="flex flex-col gap-2">
|
||||||
{items.map((item) => (
|
{items.map((item, index) => (
|
||||||
<PaymentBreakdownListItem key={item.id} item={item} />
|
<PaymentBreakdownListItem
|
||||||
|
key={item.id}
|
||||||
|
item={item}
|
||||||
|
position={index + 1}
|
||||||
|
/>
|
||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ export function PaymentOverviewWidgetView({
|
|||||||
className="text-xs data-[state=active]:bg-transparent"
|
className="text-xs data-[state=active]:bg-transparent"
|
||||||
>
|
>
|
||||||
<RiMoneyDollarCircleLine className="mr-1 size-3.5" />
|
<RiMoneyDollarCircleLine className="mr-1 size-3.5" />
|
||||||
Formas
|
Formas de pagamento
|
||||||
</TabsTrigger>
|
</TabsTrigger>
|
||||||
</TabsList>
|
</TabsList>
|
||||||
|
|
||||||
|
|||||||
@@ -1,16 +1,18 @@
|
|||||||
|
import { RiArrowDownLine, RiArrowUpLine } from "@remixicon/react";
|
||||||
import StatusDot from "@/shared/components/feedback/status-dot";
|
import StatusDot from "@/shared/components/feedback/status-dot";
|
||||||
import MoneyValues from "@/shared/components/money-values";
|
import MoneyValues from "@/shared/components/money-values";
|
||||||
import { Progress } from "@/shared/components/ui/progress";
|
import { Progress } from "@/shared/components/ui/progress";
|
||||||
|
import { formatPercentage } from "@/shared/utils/percentage";
|
||||||
|
|
||||||
type PaymentStatusCategorySectionProps = {
|
type PaymentStatusCategorySectionProps = {
|
||||||
title: string;
|
type: "income" | "expenses";
|
||||||
total: number;
|
total: number;
|
||||||
confirmed: number;
|
confirmed: number;
|
||||||
pending: number;
|
pending: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function PaymentStatusCategorySection({
|
export function PaymentStatusCategorySection({
|
||||||
title,
|
type,
|
||||||
total,
|
total,
|
||||||
confirmed,
|
confirmed,
|
||||||
pending,
|
pending,
|
||||||
@@ -19,27 +21,51 @@ export function PaymentStatusCategorySection({
|
|||||||
const absConfirmed = Math.abs(confirmed);
|
const absConfirmed = Math.abs(confirmed);
|
||||||
const confirmedPercentage =
|
const confirmedPercentage =
|
||||||
absTotal > 0 ? (absConfirmed / absTotal) * 100 : 0;
|
absTotal > 0 ? (absConfirmed / absTotal) * 100 : 0;
|
||||||
|
const income = type === "income";
|
||||||
|
const title = income ? "A receber" : "A pagar";
|
||||||
|
const confirmedLabel = income ? "recebidos" : "pagos";
|
||||||
|
const pendingLabel = income ? "a receber" : "a pagar";
|
||||||
|
const percentageLabel = income ? "recebido" : "pago";
|
||||||
|
const TitleIcon = income ? RiArrowDownLine : RiArrowUpLine;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="mt-4 space-y-3">
|
<div className="space-y-3">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<span className="text-sm font-medium text-foreground">{title}</span>
|
<span className="flex items-center gap-1.5 text-sm font-medium text-foreground">
|
||||||
|
<TitleIcon className="size-4 text-primary" aria-hidden />
|
||||||
|
{title}
|
||||||
|
</span>
|
||||||
|
<span className="flex items-center gap-2">
|
||||||
|
<span className="text-xs text-muted-foreground">
|
||||||
|
{formatPercentage(confirmedPercentage, {
|
||||||
|
minimumFractionDigits: 0,
|
||||||
|
maximumFractionDigits: 0,
|
||||||
|
})}{" "}
|
||||||
|
{percentageLabel}
|
||||||
|
</span>
|
||||||
<MoneyValues amount={total} className="font-medium" />
|
<MoneyValues amount={total} className="font-medium" />
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Progress value={confirmedPercentage} className="h-2" />
|
<Progress
|
||||||
|
value={confirmedPercentage}
|
||||||
|
className="h-2"
|
||||||
|
indicatorClassName="bg-primary"
|
||||||
|
/>
|
||||||
|
|
||||||
<div className="flex flex-col gap-1 text-sm sm:flex-row sm:items-center sm:justify-between sm:gap-4">
|
<div className="flex flex-col gap-1 text-sm sm:flex-row sm:items-center sm:justify-between sm:gap-4">
|
||||||
<div className="flex items-center gap-1.5">
|
<div className="flex items-center gap-1.5">
|
||||||
<StatusDot color="bg-primary" />
|
<StatusDot color="bg-primary" />
|
||||||
<MoneyValues amount={confirmed} className="font-medium" />
|
<MoneyValues amount={confirmed} className="font-medium" />
|
||||||
<span className="text-xs text-muted-foreground">confirmados</span>
|
<span className="text-xs text-muted-foreground">
|
||||||
|
{confirmedLabel}
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center gap-1.5">
|
<div className="flex items-center gap-1.5">
|
||||||
<StatusDot color="bg-warning/40" />
|
<StatusDot color="bg-warning/40" />
|
||||||
<MoneyValues amount={pending} className="font-medium" />
|
<MoneyValues amount={pending} className="font-medium" />
|
||||||
<span className="text-xs text-muted-foreground">pendentes</span>
|
<span className="text-xs text-muted-foreground">{pendingLabel}</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ export function PaymentStatusWidgetView({
|
|||||||
return (
|
return (
|
||||||
<CardContent className="space-y-6 px-0">
|
<CardContent className="space-y-6 px-0">
|
||||||
<PaymentStatusCategorySection
|
<PaymentStatusCategorySection
|
||||||
title="A Receber"
|
type="income"
|
||||||
total={data.income.total}
|
total={data.income.total}
|
||||||
confirmed={data.income.confirmed}
|
confirmed={data.income.confirmed}
|
||||||
pending={data.income.pending}
|
pending={data.income.pending}
|
||||||
@@ -37,7 +37,7 @@ export function PaymentStatusWidgetView({
|
|||||||
<div className="border-t" />
|
<div className="border-t" />
|
||||||
|
|
||||||
<PaymentStatusCategorySection
|
<PaymentStatusCategorySection
|
||||||
title="A Pagar"
|
type="expenses"
|
||||||
total={data.expenses.total}
|
total={data.expenses.total}
|
||||||
confirmed={data.expenses.confirmed}
|
confirmed={data.expenses.confirmed}
|
||||||
pending={data.expenses.pending}
|
pending={data.expenses.pending}
|
||||||
|
|||||||
@@ -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>
|
||||||
|
|||||||
@@ -1,20 +1,31 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { RiLineChartLine } from "@remixicon/react";
|
import {
|
||||||
|
RiArrowRightLine,
|
||||||
|
RiCalendarLine,
|
||||||
|
RiHistoryLine,
|
||||||
|
RiLineChartLine,
|
||||||
|
} 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(
|
||||||
@@ -40,24 +51,48 @@ 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="text-xs text-muted-foreground">
|
>
|
||||||
<MoneyValues amount={category.previousAmount} /> vs{" "}
|
<span className="truncate">{category.categoryName}</span>
|
||||||
|
</Link>
|
||||||
|
<p className={styles.meta}>
|
||||||
|
<span
|
||||||
|
className="inline-flex items-center gap-1"
|
||||||
|
title="Mês anterior"
|
||||||
|
>
|
||||||
|
<RiHistoryLine className="size-3.5" aria-hidden />
|
||||||
|
<span className="sr-only">Mês anterior:</span>
|
||||||
|
<MoneyValues amount={category.previousAmount} />
|
||||||
|
</span>
|
||||||
|
<RiArrowRightLine className="size-3" aria-hidden />
|
||||||
|
<span
|
||||||
|
className="inline-flex items-center gap-1 text-foreground"
|
||||||
|
title="Mês atual"
|
||||||
|
>
|
||||||
|
<RiCalendarLine
|
||||||
|
className="size-3.5 text-primary"
|
||||||
|
aria-hidden
|
||||||
|
/>
|
||||||
|
<span className="sr-only">Mês atual:</span>
|
||||||
<MoneyValues
|
<MoneyValues
|
||||||
amount={category.currentAmount}
|
amount={category.currentAmount}
|
||||||
className="font-semibold"
|
className="font-semibold"
|
||||||
/>
|
/>
|
||||||
|
</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, {
|
||||||
@@ -66,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>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -6,9 +6,11 @@ import {
|
|||||||
RiDeleteBinLine,
|
RiDeleteBinLine,
|
||||||
} from "@remixicon/react";
|
} from "@remixicon/react";
|
||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
|
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 {
|
||||||
@@ -19,6 +21,11 @@ import { TransactionDialog } from "@/features/transactions/components/dialogs/tr
|
|||||||
import { ConfirmActionDialog } from "@/shared/components/confirm-action-dialog";
|
import { ConfirmActionDialog } from "@/shared/components/confirm-action-dialog";
|
||||||
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";
|
||||||
|
import {
|
||||||
|
Tooltip,
|
||||||
|
TooltipContent,
|
||||||
|
TooltipTrigger,
|
||||||
|
} from "@/shared/components/ui/tooltip";
|
||||||
import { WidgetEmptyState } from "@/shared/components/widgets/widget-empty-state";
|
import { WidgetEmptyState } from "@/shared/components/widgets/widget-empty-state";
|
||||||
import { resolveLogoSrc } from "@/shared/lib/logo";
|
import { resolveLogoSrc } from "@/shared/lib/logo";
|
||||||
|
|
||||||
@@ -46,6 +53,24 @@ function getDateString(date: Date | string | null | undefined): string | null {
|
|||||||
return date.toISOString().slice(0, 10);
|
return date.toISOString().slice(0, 10);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function findMatchingLogo(
|
||||||
|
sourceAppName: string | null,
|
||||||
|
logoMap: Record<string, string>,
|
||||||
|
): string | null {
|
||||||
|
if (!sourceAppName) return null;
|
||||||
|
|
||||||
|
const appName = sourceAppName.toLowerCase();
|
||||||
|
if (logoMap[appName]) return resolveLogoSrc(logoMap[appName]);
|
||||||
|
|
||||||
|
for (const [name, logo] of Object.entries(logoMap)) {
|
||||||
|
if (name.includes(appName) || appName.includes(name)) {
|
||||||
|
return resolveLogoSrc(logo);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
export function InboxWidget({
|
export function InboxWidget({
|
||||||
snapshot,
|
snapshot,
|
||||||
quickActionOptions,
|
quickActionOptions,
|
||||||
@@ -149,13 +174,18 @@ export function InboxWidget({
|
|||||||
if (snapshot.pendingCount === 0) {
|
if (snapshot.pendingCount === 0) {
|
||||||
return (
|
return (
|
||||||
<WidgetEmptyState
|
<WidgetEmptyState
|
||||||
icon={<RiCheckboxCircleFill color="green" className="size-6" />}
|
icon={<RiCheckboxCircleFill className="size-6 text-success" />}
|
||||||
title="Tudo em dia"
|
title="Tudo em dia"
|
||||||
description="Nenhum pré-lançamento aguardando revisão."
|
description="Nenhum pré-lançamento aguardando revisão."
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const remainingCount = Math.max(
|
||||||
|
snapshot.pendingCount - snapshot.recentItems.length,
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col">
|
<div className="flex flex-col">
|
||||||
{snapshot.recentItems.map((item) => {
|
{snapshot.recentItems.map((item) => {
|
||||||
@@ -168,17 +198,12 @@ export function InboxWidget({
|
|||||||
parsedAmount !== null && Number.isFinite(parsedAmount)
|
parsedAmount !== null && Number.isFinite(parsedAmount)
|
||||||
? parsedAmount
|
? parsedAmount
|
||||||
: null;
|
: null;
|
||||||
const logoKey = item.sourceAppName?.toLowerCase() ?? "";
|
const logoSrc = findMatchingLogo(item.sourceAppName, snapshot.logoMap);
|
||||||
const rawLogo = snapshot.logoMap[logoKey] ?? null;
|
|
||||||
const logoSrc = resolveLogoSrc(rawLogo);
|
|
||||||
const displayLogo = logoSrc ?? DEFAULT_INBOX_APP_LOGO;
|
const displayLogo = logoSrc ?? DEFAULT_INBOX_APP_LOGO;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div key={item.id} className={styles.row}>
|
||||||
key={item.id}
|
<div className={styles.main}>
|
||||||
className="flex items-center justify-between py-1.5"
|
|
||||||
>
|
|
||||||
<div className="flex flex-1 items-center gap-2">
|
|
||||||
<Image
|
<Image
|
||||||
src={displayLogo}
|
src={displayLogo}
|
||||||
alt={item.sourceAppName ?? ""}
|
alt={item.sourceAppName ?? ""}
|
||||||
@@ -188,14 +213,12 @@ export function InboxWidget({
|
|||||||
unoptimized
|
unoptimized
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<div>
|
<div className={styles.textStack}>
|
||||||
<p className="text-sm font-medium text-foreground">
|
<p className={styles.title}>{displayName}</p>
|
||||||
{displayName.length > 30
|
<div className={styles.meta}>
|
||||||
? `${displayName.slice(0, 30)}...`
|
{item.sourceAppName && (
|
||||||
: displayName}
|
<span className="truncate">{item.sourceAppName}</span>
|
||||||
</p>
|
)}
|
||||||
<div className="flex items-center gap-2 text-xs text-muted-foreground">
|
|
||||||
{item.sourceAppName && <span>{item.sourceAppName}</span>}
|
|
||||||
<span className="text-muted-foreground/60">
|
<span className="text-muted-foreground/60">
|
||||||
{relativeTime(item.createdAt)}
|
{relativeTime(item.createdAt)}
|
||||||
</span>
|
</span>
|
||||||
@@ -203,37 +226,59 @@ export function InboxWidget({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex shrink-0 flex-col items-end">
|
<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 && (
|
||||||
|
<span className="max-w-20 text-right text-xs leading-tight text-muted-foreground">
|
||||||
|
Valor não identificado
|
||||||
|
</span>
|
||||||
)}
|
)}
|
||||||
<div className="flex items-center">
|
<div className="flex items-center">
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger asChild>
|
||||||
<Button
|
<Button
|
||||||
size="icon-sm"
|
size="icon-sm"
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
className="size-6 text-muted-foreground hover:text-foreground"
|
className="text-muted-foreground hover:text-foreground"
|
||||||
onClick={() => handleProcessRequest(item)}
|
onClick={() => handleProcessRequest(item)}
|
||||||
aria-label="Processar notificação"
|
aria-label="Lançar notificação"
|
||||||
title="Processar"
|
|
||||||
>
|
>
|
||||||
<RiCheckLine className="size-3.5" />
|
<RiCheckLine className="size-3.5" />
|
||||||
</Button>
|
</Button>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent side="top">Lançar</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger asChild>
|
||||||
<Button
|
<Button
|
||||||
size="icon-sm"
|
size="icon-sm"
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
className="size-6 text-muted-foreground hover:text-destructive"
|
className="text-muted-foreground hover:text-destructive"
|
||||||
onClick={() => handleDiscardRequest(item)}
|
onClick={() => handleDiscardRequest(item)}
|
||||||
aria-label="Descartar notificação"
|
aria-label="Descartar notificação"
|
||||||
title="Descartar"
|
|
||||||
>
|
>
|
||||||
<RiDeleteBinLine className="size-3.5" />
|
<RiDeleteBinLine className="size-3.5" />
|
||||||
</Button>
|
</Button>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent side="top">Descartar</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
|
||||||
|
{remainingCount > 0 && (
|
||||||
|
<Link
|
||||||
|
href="/inbox"
|
||||||
|
className="mt-2 inline-flex items-center justify-center text-xs font-medium text-muted-foreground transition-colors hover:text-primary"
|
||||||
|
>
|
||||||
|
+ {remainingCount} pendentes · Revisar todos
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
|
||||||
<TransactionDialog
|
<TransactionDialog
|
||||||
mode="create"
|
mode="create"
|
||||||
open={processOpen}
|
open={processOpen}
|
||||||
|
|||||||
@@ -1,7 +1,14 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { RiLineChartLine } from "@remixicon/react";
|
import { RiLineChartLine } from "@remixicon/react";
|
||||||
import { Bar, BarChart, CartesianGrid, XAxis } from "recharts";
|
import {
|
||||||
|
Bar,
|
||||||
|
CartesianGrid,
|
||||||
|
ComposedChart,
|
||||||
|
Line,
|
||||||
|
ReferenceLine,
|
||||||
|
XAxis,
|
||||||
|
} from "recharts";
|
||||||
import type { IncomeExpenseBalanceData } from "@/features/dashboard/overview/income-expense-balance-queries";
|
import type { IncomeExpenseBalanceData } from "@/features/dashboard/overview/income-expense-balance-queries";
|
||||||
import { CardContent } from "@/shared/components/ui/card";
|
import { CardContent } from "@/shared/components/ui/card";
|
||||||
import {
|
import {
|
||||||
@@ -11,6 +18,7 @@ import {
|
|||||||
} from "@/shared/components/ui/chart";
|
} from "@/shared/components/ui/chart";
|
||||||
import { WidgetEmptyState } from "@/shared/components/widgets/widget-empty-state";
|
import { WidgetEmptyState } from "@/shared/components/widgets/widget-empty-state";
|
||||||
import { formatCurrency } from "@/shared/utils/currency";
|
import { formatCurrency } from "@/shared/utils/currency";
|
||||||
|
import { formatCompactPeriodLabel } from "@/shared/utils/period";
|
||||||
|
|
||||||
type IncomeExpenseBalanceWidgetProps = {
|
type IncomeExpenseBalanceWidgetProps = {
|
||||||
data: IncomeExpenseBalanceData;
|
data: IncomeExpenseBalanceData;
|
||||||
@@ -19,15 +27,15 @@ type IncomeExpenseBalanceWidgetProps = {
|
|||||||
const chartConfig = {
|
const chartConfig = {
|
||||||
receita: {
|
receita: {
|
||||||
label: "Receita",
|
label: "Receita",
|
||||||
color: "var(--chart-1)",
|
color: "var(--success)",
|
||||||
},
|
},
|
||||||
despesa: {
|
despesa: {
|
||||||
label: "Despesa",
|
label: "Despesa",
|
||||||
color: "var(--chart-2)",
|
color: "var(--destructive)",
|
||||||
},
|
},
|
||||||
balanco: {
|
balanco: {
|
||||||
label: "Balanço",
|
label: "Balanço",
|
||||||
color: "var(--chart-3)",
|
color: "var(--primary)",
|
||||||
},
|
},
|
||||||
} satisfies ChartConfig;
|
} satisfies ChartConfig;
|
||||||
|
|
||||||
@@ -35,7 +43,7 @@ export function IncomeExpenseBalanceWidget({
|
|||||||
data,
|
data,
|
||||||
}: IncomeExpenseBalanceWidgetProps) {
|
}: IncomeExpenseBalanceWidgetProps) {
|
||||||
const chartData = data.months.map((month) => ({
|
const chartData = data.months.map((month) => ({
|
||||||
month: month.monthLabel,
|
month: formatCompactPeriodLabel(month.month).toLowerCase(),
|
||||||
receita: month.income,
|
receita: month.income,
|
||||||
despesa: month.expense,
|
despesa: month.expense,
|
||||||
balanco: month.balance,
|
balanco: month.balance,
|
||||||
@@ -59,16 +67,18 @@ export function IncomeExpenseBalanceWidget({
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<CardContent className="space-y-4 px-0">
|
<CardContent className="space-y-2 px-0">
|
||||||
<ChartContainer
|
<ChartContainer
|
||||||
config={chartConfig}
|
config={chartConfig}
|
||||||
className="h-[270px] w-full aspect-auto"
|
className="h-[270px] w-full aspect-auto"
|
||||||
>
|
>
|
||||||
<BarChart
|
<ComposedChart
|
||||||
data={chartData}
|
data={chartData}
|
||||||
margin={{ top: 20, right: 10, left: 10, bottom: 5 }}
|
margin={{ top: 20, right: 10, left: 10, bottom: 5 }}
|
||||||
|
accessibilityLayer
|
||||||
>
|
>
|
||||||
<CartesianGrid strokeDasharray="3 3" vertical={false} />
|
<CartesianGrid strokeDasharray="3 3" vertical={false} />
|
||||||
|
<ReferenceLine y={0} stroke="var(--border)" />
|
||||||
<XAxis
|
<XAxis
|
||||||
dataKey="month"
|
dataKey="month"
|
||||||
tickLine={false}
|
tickLine={false}
|
||||||
@@ -81,8 +91,15 @@ export function IncomeExpenseBalanceWidget({
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const month = payload[0]?.payload.month as string | undefined;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="rounded-lg border bg-background p-2 shadow-sm">
|
<div className="rounded-lg border bg-background p-2 shadow-sm">
|
||||||
|
{month ? (
|
||||||
|
<p className="mb-2 text-xs font-medium text-muted-foreground">
|
||||||
|
{month}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
<div className="grid gap-2">
|
<div className="grid gap-2">
|
||||||
{payload.map((entry) => {
|
{payload.map((entry) => {
|
||||||
const config =
|
const config =
|
||||||
@@ -111,7 +128,7 @@ export function IncomeExpenseBalanceWidget({
|
|||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}}
|
}}
|
||||||
cursor={{ fill: "hsl(var(--muted))", opacity: 0.3 }}
|
cursor={{ fill: "var(--muted)", opacity: 0.3 }}
|
||||||
/>
|
/>
|
||||||
<Bar
|
<Bar
|
||||||
dataKey="receita"
|
dataKey="receita"
|
||||||
@@ -125,42 +142,26 @@ export function IncomeExpenseBalanceWidget({
|
|||||||
radius={[4, 4, 0, 0]}
|
radius={[4, 4, 0, 0]}
|
||||||
maxBarSize={60}
|
maxBarSize={60}
|
||||||
/>
|
/>
|
||||||
<Bar
|
<Line
|
||||||
dataKey="balanco"
|
dataKey="balanco"
|
||||||
fill={chartConfig.balanco.color}
|
type="monotone"
|
||||||
radius={[4, 4, 0, 0]}
|
stroke={chartConfig.balanco.color}
|
||||||
maxBarSize={60}
|
strokeWidth={2}
|
||||||
|
dot={{ fill: chartConfig.balanco.color, r: 3 }}
|
||||||
|
activeDot={{ r: 5 }}
|
||||||
/>
|
/>
|
||||||
</BarChart>
|
</ComposedChart>
|
||||||
</ChartContainer>
|
</ChartContainer>
|
||||||
<div className="flex items-center justify-center gap-6">
|
<div className="flex flex-wrap items-center justify-center gap-x-4 gap-y-1 text-xs text-muted-foreground">
|
||||||
<div className="flex items-center gap-2">
|
{Object.values(chartConfig).map((config) => (
|
||||||
|
<div key={config.label} className="flex items-center gap-1.5">
|
||||||
<div
|
<div
|
||||||
className="size-2 rounded-full"
|
className="size-2 rounded-full"
|
||||||
style={{ backgroundColor: chartConfig.receita.color }}
|
style={{ backgroundColor: config.color }}
|
||||||
/>
|
/>
|
||||||
<span className="text-sm text-muted-foreground">
|
<span>{config.label}</span>
|
||||||
{chartConfig.receita.label}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<div
|
|
||||||
className="size-2 rounded-full"
|
|
||||||
style={{ backgroundColor: chartConfig.despesa.color }}
|
|
||||||
/>
|
|
||||||
<span className="text-sm text-muted-foreground">
|
|
||||||
{chartConfig.despesa.label}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<div
|
|
||||||
className="size-2 rounded-full"
|
|
||||||
style={{ backgroundColor: chartConfig.balanco.color }}
|
|
||||||
/>
|
|
||||||
<span className="text-sm text-muted-foreground">
|
|
||||||
{chartConfig.balanco.label}
|
|
||||||
</span>
|
|
||||||
</div>
|
</div>
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
);
|
);
|
||||||
|
|||||||