Compare commits
241 Commits
fee2a2c9f5
...
v2.7.11
| 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 | ||
|
|
e50eeba36e | ||
|
|
26cb18a9ad | ||
|
|
382727a96d | ||
|
|
0df648c7f3 | ||
|
|
27f361923c | ||
|
|
60b2612e8a | ||
|
|
0171b0ce2f | ||
|
|
311369f81b | ||
|
|
ef2c8c50e8 | ||
|
|
5319d8a5a6 | ||
|
|
37247e319c | ||
|
|
766af2b347 | ||
|
|
5dcd30010e | ||
|
|
d589df6993 | ||
|
|
8a19f0f311 | ||
|
|
887885cd98 | ||
|
|
7a0e33efd8 | ||
|
|
b9557961e5 | ||
|
|
53c8e47981 | ||
|
|
adc9292cd8 | ||
|
|
b95d6f6752 | ||
|
|
c9f667a065 | ||
|
|
01d9c6ea05 | ||
|
|
d383d2db91 | ||
|
|
7a8d01debe | ||
|
|
3be15d3b15 | ||
|
|
fea9cf81d8 | ||
|
|
7a10d431ab | ||
|
|
b7343eb235 | ||
|
|
3bcc392f38 | ||
|
|
5241de44af | ||
|
|
1a75662120 | ||
|
|
7ca3f92467 | ||
|
|
6b044f3bc5 | ||
|
|
4e8f9cc5fa | ||
|
|
b6659ef66e | ||
|
|
21d7396c80 | ||
|
|
3a768bc8ba | ||
|
|
8a03a50132 | ||
|
|
246bb14a00 | ||
|
|
86bcffec66 | ||
|
|
81e7151876 | ||
|
|
0bb664884a | ||
|
|
f02958df1d | ||
|
|
c4c52c02ab | ||
|
|
c9239c4f3c | ||
|
|
7128cc0ae7 | ||
|
|
467f71493d | ||
|
|
0cec10ede3 | ||
|
|
a6fba5f953 | ||
|
|
18893bfe02 | ||
|
|
7fdf9e2876 | ||
|
|
7d0781b035 | ||
|
|
b9b843b9db | ||
|
|
01215b3124 | ||
|
|
d70223e7b3 | ||
|
|
6ea064e1bd | ||
|
|
9c0669a152 | ||
|
|
b2d4b29cb5 | ||
|
|
1df2ba787d | ||
|
|
e5d9b66cca | ||
|
|
37edb1b76d | ||
|
|
6288f5f8d4 | ||
|
|
57ac326c2a | ||
|
|
dccc18b1c1 | ||
|
|
0cb01a1d4c | ||
|
|
51652da4f8 | ||
|
|
7a74f9405e | ||
|
|
94bf93194f | ||
|
|
d55173e8c1 | ||
|
|
4a73088c09 | ||
|
|
eaa20448a8 | ||
|
|
367d78d43d | ||
|
|
2fc6d11d78 | ||
|
|
0f5c735be0 | ||
|
|
4bea6330bf | ||
|
|
8389752172 | ||
|
|
19b5aa00ee | ||
|
|
863ccc0fd2 | ||
|
|
29d99cbedb | ||
|
|
dbeb98bbe4 | ||
|
|
c0436dc2ac | ||
|
|
e1e76fadc0 | ||
|
|
9b2c15ef7d | ||
|
|
fbe3fceb9f | ||
|
|
39f3cd8b20 | ||
|
|
791fec7751 | ||
|
|
114e2b4011 | ||
|
|
f15a003cef | ||
|
|
7f07a9cbf6 | ||
|
|
5fa234884e | ||
|
|
b453b432ed | ||
|
|
7f05d2a681 | ||
|
|
b14f487824 | ||
|
|
5b03824a72 | ||
|
|
74dda549f5 | ||
|
|
137b63f256 | ||
|
|
f747405264 | ||
|
|
cbc17c8513 | ||
|
|
c41fafc319 | ||
|
|
0bc3f06b77 | ||
|
|
2f68bcf039 | ||
|
|
41dcd5cec9 | ||
|
|
6391f07eb6 | ||
|
|
ae9dd364c4 | ||
|
|
e005add233 | ||
|
|
6d81ff8b53 | ||
|
|
5d84ae928a | ||
|
|
ba05985725 | ||
|
|
3e80d5995b | ||
|
|
68daae7926 | ||
|
|
9413c470a8 | ||
|
|
ad1b0aa979 | ||
|
|
4d9a1c0a35 | ||
|
|
5635705c56 | ||
|
|
4c97ed569d | ||
|
|
22a88de993 | ||
|
|
9456aa98bc | ||
|
|
21c6a8d9d0 | ||
|
|
c29ffa9a12 | ||
|
|
8875de843b | ||
|
|
679ea752bb | ||
|
|
1161e97d9e | ||
|
|
55d7dedd9a | ||
|
|
ad2752b7b0 | ||
|
|
58db357cde | ||
|
|
99a9ff5512 | ||
|
|
5bcf4f69d3 | ||
|
|
95099c1a94 | ||
|
|
94912f7edc | ||
|
|
bf6adfa3f1 | ||
|
|
e4b9dd4254 | ||
|
|
f1907c8697 | ||
|
|
805bcb863d | ||
|
|
11b4f8940f | ||
|
|
fba9686fdb | ||
|
|
9b8ac9f71f | ||
|
|
fa41c78a39 | ||
|
|
5f7bfb98da | ||
|
|
9ecafdb15f | ||
|
|
e8cc673e52 | ||
|
|
3bd8117b65 | ||
|
|
a7268d8f05 | ||
|
|
1f9098879e | ||
|
|
7a3bff52ac | ||
|
|
dfb4126b12 | ||
|
|
ffead579fa | ||
|
|
aa85cf8b29 | ||
|
|
9a7ae0fa3d | ||
|
|
98fe6a0f4f | ||
|
|
d10eae13e5 | ||
|
|
43697b4fd2 | ||
|
|
27e3ba5f0d | ||
|
|
31485eec8f | ||
|
|
3be64aa8d0 | ||
|
|
85f6dcfc22 | ||
|
|
df996df93d | ||
|
|
10afef9fec | ||
|
|
fd4d90a53e | ||
|
|
a24406271c | ||
|
|
a09942e3d8 | ||
|
|
96febd5904 | ||
|
|
c3cfbc878c | ||
|
|
55bbfabe9f | ||
|
|
f5cdae4853 | ||
|
|
5c4995961c | ||
|
|
1b4dfaaba7 | ||
|
|
549a5bdba1 | ||
|
|
acaf9d5c27 | ||
|
|
e4c6a91350 | ||
|
|
ba369e8a83 | ||
|
|
d01bc8a669 | ||
|
|
e024e0d54e | ||
|
|
c44089169f | ||
|
|
d04e30e3c9 | ||
|
|
229b6c5bc0 | ||
|
|
c3b133d8d9 | ||
|
|
e9a2ab1782 | ||
|
|
c7d6e23398 | ||
|
|
0514efb1c4 | ||
|
|
e32fb85006 | ||
|
|
96df6a1798 | ||
|
|
1f8a97bd16 | ||
|
|
0ab3298cef | ||
|
|
cad41680eb | ||
|
|
3b00f328c5 | ||
|
|
20d0c3e0a7 | ||
|
|
71b5a004e3 | ||
|
|
65b1506d75 | ||
|
|
2a458d5a3c | ||
|
|
f418987f47 | ||
|
|
59b4dea071 | ||
|
|
6ce132fe0c | ||
|
|
49731238e4 | ||
|
|
c5df97f7aa | ||
|
|
3476fda4db | ||
|
|
519b673ae5 | ||
|
|
303b8bedd4 | ||
|
|
f2b9b16896 | ||
|
|
6eba35542b | ||
|
|
f5e95ffba6 | ||
|
|
a75bb86eec | ||
|
|
a3b858621f |
34
.env.example
@@ -3,10 +3,10 @@
|
|||||||
# ============================================
|
# ============================================
|
||||||
|
|
||||||
# === Database ===
|
# === Database ===
|
||||||
# PostgreSQL local (Docker): use host "db"
|
# Desenvolvimento local (pnpm dev): use host "localhost" (padrão abaixo)
|
||||||
# PostgreSQL local (sem Docker): use host "localhost"
|
# Docker Compose completo: o compose.yml define DATABASE_URL automaticamente com host "db"
|
||||||
# PostgreSQL remoto: use URL completa do provider
|
# PostgreSQL remoto: use URL completa do provider
|
||||||
DATABASE_URL=postgresql://openmonetis:openmonetis_dev_password@db:5432/openmonetis_db
|
DATABASE_URL=postgresql://openmonetis:openmonetis_dev_password@localhost:5432/openmonetis_db
|
||||||
|
|
||||||
# Credenciais do PostgreSQL (apenas para Docker local) - Alterar
|
# Credenciais do PostgreSQL (apenas para Docker local) - Alterar
|
||||||
POSTGRES_USER=openmonetis
|
POSTGRES_USER=openmonetis
|
||||||
@@ -18,6 +18,18 @@ POSTGRES_DB=openmonetis_db
|
|||||||
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
|
||||||
|
DISABLE_SIGNUP=false
|
||||||
|
|
||||||
|
# Duração de sessões persistentes quando "Manter conectado" estiver marcado
|
||||||
|
AUTH_SESSION_EXPIRES_IN_DAYS=30
|
||||||
|
AUTH_SESSION_UPDATE_AGE_HOURS=24
|
||||||
|
|
||||||
# === Portas ===
|
# === Portas ===
|
||||||
APP_PORT=3000
|
APP_PORT=3000
|
||||||
DB_PORT=5432
|
DB_PORT=5432
|
||||||
@@ -44,8 +56,22 @@ GOOGLE_CLIENT_SECRET=
|
|||||||
# Se não definido, todas as rotas ficam acessíveis.
|
# Se não definido, todas as rotas ficam acessíveis.
|
||||||
# PUBLIC_DOMAIN=openmonetis.com
|
# PUBLIC_DOMAIN=openmonetis.com
|
||||||
|
|
||||||
|
# === Analytics (Opcional) ===
|
||||||
|
# Umami: https://umami.is — self-hosted ou cloud
|
||||||
|
UMAMI_URL=
|
||||||
|
UMAMI_WEBSITE_ID=
|
||||||
|
UMAMI_DOMAINS=
|
||||||
|
|
||||||
# === AI Providers (Opcional) ===
|
# === AI Providers (Opcional) ===
|
||||||
ANTHROPIC_API_KEY=
|
ANTHROPIC_API_KEY=
|
||||||
OPENAI_API_KEY=
|
OPENAI_API_KEY=
|
||||||
GOOGLE_GENERATIVE_AI_API_KEY=
|
GOOGLE_GENERATIVE_AI_API_KEY=
|
||||||
OPENROUTER_API_KEY=
|
MINIMAX_API_KEY=
|
||||||
|
OPENROUTER_API_KEY=
|
||||||
|
OLLAMA_BASE_URL=http://127.0.0.1:11434/v1
|
||||||
|
OLLAMA_API_KEY=
|
||||||
|
|
||||||
|
# === Logo.dev (Opcional) ===
|
||||||
|
# Logos automáticos de estabelecimentos. Cadastre em https://www.logo.dev
|
||||||
|
LOGO_DEV_TOKEN=
|
||||||
|
LOGO_DEV_SECRET_KEY=
|
||||||
|
|||||||
4
.gitattributes
vendored
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
# Força LF para arquivos que precisam de line endings Unix no container
|
||||||
|
*.sh text eol=lf
|
||||||
|
docker-entrypoint.sh text eol=lf
|
||||||
|
Dockerfile text eol=lf
|
||||||
58
.github/copilot-instructions.md
vendored
@@ -1,58 +0,0 @@
|
|||||||
# AI Coding Assistant Instructions for OpenMonetis
|
|
||||||
|
|
||||||
## Project Overview
|
|
||||||
|
|
||||||
OpenMonetis is a self-hosted personal finance management application built with Next.js 16, TypeScript, PostgreSQL, and Drizzle ORM. It provides manual transaction tracking, account management, budgeting, and financial insights with a Portuguese interface.
|
|
||||||
|
|
||||||
## Architecture
|
|
||||||
|
|
||||||
- **Frontend**: Next.js App Router with React 19, shadcn/ui components, Tailwind CSS
|
|
||||||
- **Backend**: Server actions in Next.js, API routes for auth/health
|
|
||||||
- **Database**: PostgreSQL with Drizzle ORM, schema in `db/schema.ts`
|
|
||||||
- **Auth**: Better Auth (OAuth + email magic links)
|
|
||||||
- **Deployment**: Docker multi-stage build, health checks
|
|
||||||
|
|
||||||
## Key Patterns
|
|
||||||
|
|
||||||
- **Server Actions**: Use `"use server"` for mutations, validate with Zod schemas, handle errors with `handleActionError`
|
|
||||||
- **Database Queries**: Use Drizzle's query API with relations, e.g., `db.query.lancamentos.findMany({ with: { categoria: true } })`
|
|
||||||
- **Authentication**: Import from `lib/auth/server`, redirect on failure
|
|
||||||
- **Revalidation**: Call `revalidateForEntity("lancamentos")` after mutations
|
|
||||||
- **Portuguese Naming**: DB fields like `nome`, `tipo_conta`, `pagador` (payer), `lancamento` (transaction)
|
|
||||||
- **Component Structure**: Feature-based folders in `components/`, shared UI in `components/ui/`
|
|
||||||
|
|
||||||
## Development Workflow
|
|
||||||
|
|
||||||
- **Start Dev**: `pnpm dev` (Turbopack), `docker compose up db -d` for DB
|
|
||||||
- **Database**: `pnpm db:push` to sync schema, `pnpm db:studio` for visual editor
|
|
||||||
- **Build**: `pnpm build`, `pnpm start` for production
|
|
||||||
- **Docker**: `pnpm docker:up` for full stack, `pnpm docker:logs` for monitoring
|
|
||||||
|
|
||||||
## Common Tasks
|
|
||||||
|
|
||||||
- **Add Transaction**: Create server action in `app/(dashboard)/lancamentos/actions.ts`, validate with Zod, insert via Drizzle
|
|
||||||
- **New Entity**: Add to `db/schema.ts`, define relations, create CRUD actions in `lib/[entity]/actions.ts`
|
|
||||||
- **UI Component**: Use shadcn/ui, place in `components/[feature]/`, export from `components/ui/`
|
|
||||||
- **API Route**: Add to `app/api/`, use `getUserSession()` for auth
|
|
||||||
|
|
||||||
## Conventions
|
|
||||||
|
|
||||||
- **Imports**: Absolute paths with `@/`, group by external/internal
|
|
||||||
- **Error Handling**: Return `{ success: false, error: string }` from actions
|
|
||||||
- **Currency**: Store as decimal strings (e.g., "123.45"), convert to cents for calculations
|
|
||||||
- **Periods**: Format as "YYYY-MM", use `parsePeriodParam()` for URL params
|
|
||||||
- **Notifications**: Send emails via `sendPagadorAutoEmails()` for payer updates
|
|
||||||
|
|
||||||
## External Integrations
|
|
||||||
|
|
||||||
- **Better Auth**: Config in `lib/auth/config.ts`, session handling
|
|
||||||
- **Drizzle**: Migrations in `drizzle/`, studio at `pnpm db:studio`
|
|
||||||
- **AI Features**: Use `@ai-sdk/*` for insights, configured in environment
|
|
||||||
- **Email**: Resend for notifications, configured via `RESEND_API_KEY`
|
|
||||||
|
|
||||||
## File Examples
|
|
||||||
|
|
||||||
- Schema: `db/schema.ts` (relations, indexes)
|
|
||||||
- Actions: `app/(dashboard)/lancamentos/actions.ts` (CRUD with validation)
|
|
||||||
- Components: `components/lancamentos/page/lancamentos-page.tsx` (client component)
|
|
||||||
- Utils: `lib/lancamentos/page-helpers.ts` (data transformation)
|
|
||||||
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
|
||||||
65
.github/workflows/docker-publish.yml
vendored
@@ -1,65 +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:
|
|
||||||
build-and-push:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
packages: write
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Checkout repository
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- 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 }}
|
|
||||||
159
.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@v4
|
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
|
||||||
|
|||||||
2
.gitignore
vendored
@@ -105,7 +105,7 @@ docker-compose.override.yml
|
|||||||
.gemini/
|
.gemini/
|
||||||
.cursor/
|
.cursor/
|
||||||
QWEN.md
|
QWEN.md
|
||||||
AGENTS.md
|
.codex
|
||||||
# === Backups locais ===
|
# === Backups locais ===
|
||||||
/backup/
|
/backup/
|
||||||
|
|
||||||
|
|||||||
35
.vscode/settings.json
vendored
@@ -1,35 +0,0 @@
|
|||||||
{
|
|
||||||
"files.exclude": {
|
|
||||||
"**/.git": true,
|
|
||||||
"**/.svn": true,
|
|
||||||
"**/.hg": true,
|
|
||||||
"**/.DS_Store": true,
|
|
||||||
"**/Thumbs.db": true,
|
|
||||||
"**/node_modules": true,
|
|
||||||
"node_modules": true,
|
|
||||||
"**/.vscode": true,
|
|
||||||
".vscode": true,
|
|
||||||
"**/.next": true,
|
|
||||||
".next": true
|
|
||||||
},
|
|
||||||
"explorerExclude.backup": {},
|
|
||||||
"editor.defaultFormatter": "biomejs.biome",
|
|
||||||
"editor.formatOnSave": true,
|
|
||||||
"editor.codeActionsOnSave": {
|
|
||||||
"source.organizeImports": "never",
|
|
||||||
"source.organizeImports.biome": "always",
|
|
||||||
"source.fixAll": "never",
|
|
||||||
"source.fixAll.biome": "always",
|
|
||||||
"source.fixAll.eslint": "never"
|
|
||||||
},
|
|
||||||
"[json]": {
|
|
||||||
"editor.defaultFormatter": "biomejs.biome"
|
|
||||||
},
|
|
||||||
"eslint.enable": false,
|
|
||||||
"prettier.enable": false,
|
|
||||||
"typescript.preferences.organizeImportsCollation": "ordinal",
|
|
||||||
"editor.fontSize": 15,
|
|
||||||
"[jsonc]": {
|
|
||||||
"editor.defaultFormatter": "vscode.json-language-features"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
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.
|
||||||
|
|
||||||
|
---
|
||||||
845
CHANGELOG.md
103
CLAUDE.md
@@ -16,9 +16,10 @@
|
|||||||
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.
|
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.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -44,6 +45,10 @@ Use esta pergunta:
|
|||||||
|
|
||||||
Se um contrato cruza dominios, ele deve morar em `src/shared/`.
|
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:
|
Exemplos comuns:
|
||||||
|
|
||||||
- auth: `src/shared/lib/auth/*`
|
- auth: `src/shared/lib/auth/*`
|
||||||
@@ -80,6 +85,7 @@ src/
|
|||||||
│ │ ├── insights/
|
│ │ ├── insights/
|
||||||
│ │ ├── calendar/
|
│ │ ├── calendar/
|
||||||
│ │ ├── inbox/
|
│ │ ├── inbox/
|
||||||
|
│ │ ├── attachments/
|
||||||
│ │ ├── changelog/
|
│ │ ├── changelog/
|
||||||
│ │ ├── reports/
|
│ │ ├── reports/
|
||||||
│ │ │ ├── category-trends/
|
│ │ │ ├── category-trends/
|
||||||
@@ -91,7 +97,7 @@ src/
|
|||||||
│ ├── api/
|
│ ├── api/
|
||||||
│ ├── globals.css
|
│ ├── globals.css
|
||||||
│ └── layout.tsx
|
│ └── layout.tsx
|
||||||
├── features/
|
├── features/ # cada feature segue: actions.ts, queries.ts, actions/, components/, hooks/, lib/
|
||||||
│ ├── auth/
|
│ ├── auth/
|
||||||
│ ├── landing/
|
│ ├── landing/
|
||||||
│ ├── dashboard/
|
│ ├── dashboard/
|
||||||
@@ -106,13 +112,17 @@ src/
|
|||||||
│ ├── insights/
|
│ ├── insights/
|
||||||
│ ├── calendar/
|
│ ├── calendar/
|
||||||
│ ├── inbox/
|
│ ├── inbox/
|
||||||
|
│ ├── attachments/
|
||||||
│ ├── reports/
|
│ ├── reports/
|
||||||
│ └── settings/
|
│ └── settings/
|
||||||
├── shared/
|
├── shared/
|
||||||
│ ├── components/
|
│ ├── components/
|
||||||
│ │ ├── ui/
|
│ │ ├── ui/ # shadcn/ui primitives
|
||||||
│ │ ├── navigation/
|
│ │ ├── navigation/ # navbar, sidebar, breadcrumbs
|
||||||
│ │ ├── providers/
|
│ │ ├── 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/
|
│ │ ├── month-picker/
|
||||||
│ │ ├── logo-picker/
|
│ │ ├── logo-picker/
|
||||||
│ │ ├── calculator/
|
│ │ ├── calculator/
|
||||||
@@ -127,34 +137,56 @@ src/
|
|||||||
│ │ ├── calculator/
|
│ │ ├── calculator/
|
||||||
│ │ ├── categories/
|
│ │ ├── categories/
|
||||||
│ │ ├── email/
|
│ │ ├── email/
|
||||||
|
│ │ ├── import/
|
||||||
│ │ ├── installments/
|
│ │ ├── installments/
|
||||||
│ │ ├── invoices/
|
│ │ ├── invoices/
|
||||||
│ │ ├── logo/
|
│ │ ├── logo/
|
||||||
|
│ │ ├── notifications/
|
||||||
│ │ ├── payers/
|
│ │ ├── payers/
|
||||||
│ │ ├── schemas/
|
│ │ ├── schemas/
|
||||||
|
│ │ ├── storage/
|
||||||
│ │ ├── transfers/
|
│ │ ├── transfers/
|
||||||
│ │ ├── types/
|
│ │ ├── types/
|
||||||
|
│ │ ├── version/
|
||||||
│ │ └── db.ts
|
│ │ └── db.ts
|
||||||
│ └── utils/
|
│ └── utils/
|
||||||
│ ├── period/
|
│ ├── period/
|
||||||
|
│ ├── calculator.ts
|
||||||
|
│ ├── calendar.ts
|
||||||
|
│ ├── category-colors.ts
|
||||||
│ ├── currency.ts
|
│ ├── currency.ts
|
||||||
│ ├── date.ts
|
│ ├── date.ts
|
||||||
|
│ ├── export-branding.ts
|
||||||
|
│ ├── fetch-json.ts
|
||||||
│ ├── financial-dates.ts
|
│ ├── financial-dates.ts
|
||||||
│ ├── percentage.ts
|
│ ├── icons.tsx
|
||||||
│ ├── category-colors.ts
|
│ ├── id.ts
|
||||||
│ ├── calendar.ts
|
│ ├── initials.ts
|
||||||
│ ├── math.ts
|
│ ├── math.ts
|
||||||
│ ├── number.ts
|
│ ├── number.ts
|
||||||
|
│ ├── percentage.ts
|
||||||
│ ├── string.ts
|
│ ├── string.ts
|
||||||
│ ├── initials.ts
|
│ └── ui.ts
|
||||||
│ ├── icons.tsx
|
|
||||||
│ ├── export-branding.ts
|
|
||||||
│ ├── ui.ts
|
|
||||||
│ └── calculator.ts
|
|
||||||
└── db/
|
└── db/
|
||||||
└── schema.ts
|
└── 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
|
## Import Patterns
|
||||||
@@ -210,7 +242,9 @@ Layouts, `loading.tsx` e metadata continuam em `src/app/`.
|
|||||||
| `contas` | `accounts` |
|
| `contas` | `accounts` |
|
||||||
| `categorias` | `categories` |
|
| `categorias` | `categories` |
|
||||||
| `orcamentos` | `budgets` |
|
| `orcamentos` | `budgets` |
|
||||||
| `pagadores` | `payers` |
|
| `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` |
|
| `anotacoes` | `notes` |
|
||||||
| `calendario` | `calendar` |
|
| `calendario` | `calendar` |
|
||||||
| `ajustes` | `settings` |
|
| `ajustes` | `settings` |
|
||||||
@@ -290,9 +324,11 @@ export async function fetchData(userId: string, period: string) {
|
|||||||
2. Criar a feature em `src/features/<feature>/`
|
2. Criar a feature em `src/features/<feature>/`
|
||||||
3. Separar:
|
3. Separar:
|
||||||
- `components/`
|
- `components/`
|
||||||
- `queries.ts`
|
- `queries.ts` (entry point de leitura)
|
||||||
- `actions.ts`
|
- `actions.ts` (entry point de Server Actions; vira barrel quando crescer e migrar para `actions/`)
|
||||||
- `types.ts` ou `schemas.ts` quando fizer sentido
|
- `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
|
4. Extrair para `src/shared/` tudo que for reutilizavel
|
||||||
5. Atualizar navegacao e `revalidateForEntity()` se a feature tiver CRUD
|
5. Atualizar navegacao e `revalidateForEntity()` se a feature tiver CRUD
|
||||||
6. Rodar:
|
6. Rodar:
|
||||||
@@ -302,18 +338,29 @@ export async function fetchData(userId: string, period: string) {
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Response Style
|
## Security Rules
|
||||||
|
|
||||||
Quando o time pedir avaliacao de plano ou feature:
|
Regras aplicadas automaticamente ao gerar codigo.
|
||||||
|
|
||||||
1. Responder em portugues simples.
|
### Secrets
|
||||||
2. Listar 3-5 problemas principais.
|
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.
|
||||||
3. Fechar com decisao pratica:
|
|
||||||
- aprova agora
|
|
||||||
- nao aprova agora
|
|
||||||
- o que ajustar antes de comecar codigo
|
|
||||||
|
|
||||||
Exemplo:
|
### 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.
|
||||||
|
|
||||||
- "Nao aprovaria para comecar codigo imediatamente."
|
### Input & Output
|
||||||
- "Primeiro ajustaria o doc com estes 5 pontos."
|
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.
|
||||||
|
|
||||||
|
---
|
||||||
|
|||||||
178
DESIGN.md
Normal file
@@ -0,0 +1,178 @@
|
|||||||
|
# Design System do OpenMonetis
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
## 1. Direção visual
|
||||||
|
|
||||||
|
O OpenMonetis busca tornar a gestão financeira clara e acolhedora. A interface
|
||||||
|
usa superfícies quentes, poucos elementos decorativos e uma cor laranja de
|
||||||
|
destaque para orientar o olhar sem transformar toda ação em urgência.
|
||||||
|
|
||||||
|
Princípios:
|
||||||
|
|
||||||
|
- priorizar legibilidade e hierarquia em telas com muitos dados;
|
||||||
|
- usar laranja para ações principais, seleção e foco;
|
||||||
|
- 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.
|
||||||
|
|
||||||
|
## 2. Fonte de verdade
|
||||||
|
|
||||||
|
Os tokens globais estão definidos em
|
||||||
|
[`src/app/globals.css`](./src/app/globals.css). Componentes reutilizáveis ficam
|
||||||
|
em [`src/shared/components/ui/`](./src/shared/components/ui/) e seguem o padrão
|
||||||
|
do shadcn/ui com Radix UI e Tailwind CSS 4.
|
||||||
|
|
||||||
|
Ao implementar uma tela:
|
||||||
|
|
||||||
|
1. use classes semânticas como `bg-background`, `bg-card`, `text-foreground`,
|
||||||
|
`text-muted-foreground`, `border-border` e `ring-ring`;
|
||||||
|
2. reutilize os componentes em `src/shared/components/ui/`;
|
||||||
|
3. evite cores hexadecimais e valores arbitrários quando já existir um token;
|
||||||
|
4. valide os dois temas antes de concluir a alteração.
|
||||||
|
|
||||||
|
## 3. Cores
|
||||||
|
|
||||||
|
A paleta é definida em OKLCH para manter uma percepção de contraste mais
|
||||||
|
consistente. Não copie os valores para componentes: use os tokens semânticos.
|
||||||
|
|
||||||
|
| Token | Papel |
|
||||||
|
|---|---|
|
||||||
|
| `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 |
|
||||||
|
|
||||||
|
### Gráficos
|
||||||
|
|
||||||
|
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
|
||||||
|
meio de distinguir uma série: inclua legenda, rótulo ou tooltip.
|
||||||
|
|
||||||
|
### Tema escuro
|
||||||
|
|
||||||
|
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:`.
|
||||||
|
|
||||||
|
## 4. Tipografia
|
||||||
|
|
||||||
|
A família principal é **Bricolage Grotesque**, carregada com `next/font` em
|
||||||
|
[`public/fonts/font_index.ts`](./public/fonts/font_index.ts). Os pesos
|
||||||
|
disponíveis são `500`, `600` e `700`, com fallback para Arial e fontes sans-serif
|
||||||
|
do sistema.
|
||||||
|
|
||||||
|
Diretrizes:
|
||||||
|
|
||||||
|
- corpo e controles: `text-sm` ou `text-base`;
|
||||||
|
- descrições e metadados: `text-sm text-muted-foreground`;
|
||||||
|
- títulos de card: `text-base font-medium`;
|
||||||
|
- títulos de modal: `text-lg font-semibold`;
|
||||||
|
- títulos de página: hierarquia responsiva conforme a densidade da tela;
|
||||||
|
- números financeiros: destaque por peso e alinhamento, sem depender apenas da
|
||||||
|
cor.
|
||||||
|
|
||||||
|
## 5. Espaçamento, raio e elevação
|
||||||
|
|
||||||
|
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`.
|
||||||
|
|
||||||
|
Sombras também são tokens. Cards comuns usam `shadow-xs`; menus, tooltips e
|
||||||
|
modais podem subir de nível conforme a necessidade. Evite adicionar sombra forte
|
||||||
|
a cada bloco: bordas e diferença de superfície devem resolver a maior parte da
|
||||||
|
hierarquia.
|
||||||
|
|
||||||
|
## 6. Componentes
|
||||||
|
|
||||||
|
### Botões
|
||||||
|
|
||||||
|
Use [`Button`](./src/shared/components/ui/button.tsx) e suas variantes:
|
||||||
|
|
||||||
|
| 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 |
|
||||||
|
|
||||||
|
Não coloque duas ações `default` competindo na mesma região. Para ícones sem
|
||||||
|
rótulo visível, inclua `aria-label` ou texto apenas para leitores de tela.
|
||||||
|
|
||||||
|
### Cards
|
||||||
|
|
||||||
|
Use [`Card`](./src/shared/components/ui/card.tsx) para agrupar informações
|
||||||
|
relacionadas. O componente já define fundo, borda, sombra leve, raio e destaque
|
||||||
|
de hover. Não transforme todo conteúdo em card: listas densas e tabelas podem
|
||||||
|
usar uma única superfície.
|
||||||
|
|
||||||
|
### Formulários
|
||||||
|
|
||||||
|
Campos devem usar os componentes compartilhados, como `Input`, `Select`,
|
||||||
|
`Checkbox`, `Switch` e `DatePicker`. Eles já aplicam foco com `ring`, estados
|
||||||
|
desabilitados e integração visual com os temas. Sempre associe controles a
|
||||||
|
`Label` e apresente erros próximos ao campo correspondente.
|
||||||
|
|
||||||
|
### Diálogos
|
||||||
|
|
||||||
|
Use [`Dialog`](./src/shared/components/ui/dialog.tsx) para tarefas focadas. Em
|
||||||
|
mobile, o conteúdo respeita a largura disponível; em telas maiores, o modal pode
|
||||||
|
ganhar mais espaço. Botões do rodapé devem preservar a ordem e a hierarquia da
|
||||||
|
ação principal.
|
||||||
|
|
||||||
|
### Feedback
|
||||||
|
|
||||||
|
Use toast para retorno breve, `Alert` para contexto persistente e componentes em
|
||||||
|
[`src/shared/components/feedback/`](./src/shared/components/feedback/) para
|
||||||
|
estados vazios, status e confirmações. Textos visíveis ao usuário devem estar em
|
||||||
|
português claro.
|
||||||
|
|
||||||
|
## 7. Layout e navegação
|
||||||
|
|
||||||
|
As páginas protegidas usam uma navbar fixa e um contêiner central com largura
|
||||||
|
máxima `max-w-8xl`, padding lateral responsivo e espaçamento vertical enxuto. A
|
||||||
|
navegação principal fica em
|
||||||
|
[`src/shared/components/navigation/navbar/`](./src/shared/components/navigation/navbar/).
|
||||||
|
|
||||||
|
Padrões:
|
||||||
|
|
||||||
|
- 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.
|
||||||
|
|
||||||
|
## 8. Acessibilidade
|
||||||
|
|
||||||
|
- mantenha foco visível com os tokens `ring`;
|
||||||
|
- use HTML semântico antes de adicionar ARIA;
|
||||||
|
- não comunique estado apenas por cor;
|
||||||
|
- associe labels a inputs;
|
||||||
|
- forneça nome acessível para botões de ícone;
|
||||||
|
- confira contraste e navegação por teclado nos temas claro e escuro;
|
||||||
|
- mantenha áreas de toque confortáveis em mobile.
|
||||||
|
|
||||||
|
## 9. Checklist de revisão visual
|
||||||
|
|
||||||
|
- O componente compartilhado existente foi reutilizado?
|
||||||
|
- As cores usam tokens semânticos?
|
||||||
|
- A tela funciona em tema claro e escuro?
|
||||||
|
- O layout continua legível em mobile?
|
||||||
|
- Foco, labels e nomes acessíveis estão presentes?
|
||||||
|
- Estados vazio, carregando, erro e sucesso foram considerados?
|
||||||
|
- Valores financeiros continuam fáceis de comparar?
|
||||||
67
Dockerfile
@@ -5,13 +5,16 @@
|
|||||||
# ============================================
|
# ============================================
|
||||||
FROM node:22-alpine AS deps
|
FROM node:22-alpine AS deps
|
||||||
|
|
||||||
# Instalar pnpm globalmente
|
ARG PNPM_VERSION=11.1.3
|
||||||
RUN corepack enable && corepack prepare pnpm@latest --activate
|
RUN corepack enable && corepack prepare pnpm@${PNPM_VERSION} --activate
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
# Copiar apenas arquivos de dependências para aproveitar cache
|
# Copiar apenas arquivos de dependências para aproveitar cache
|
||||||
COPY package.json pnpm-lock.yaml* ./
|
COPY package.json pnpm-lock.yaml* pnpm-workspace.yaml ./
|
||||||
|
|
||||||
|
# Criar pasta public para o postinstall do pdfjs-dist
|
||||||
|
RUN mkdir -p public
|
||||||
|
|
||||||
# Instalar dependências (production + dev para o build)
|
# Instalar dependências (production + dev para o build)
|
||||||
RUN pnpm install --frozen-lockfile
|
RUN pnpm install --frozen-lockfile
|
||||||
@@ -21,8 +24,8 @@ RUN pnpm install --frozen-lockfile
|
|||||||
# ============================================
|
# ============================================
|
||||||
FROM node:22-alpine AS builder
|
FROM node:22-alpine AS builder
|
||||||
|
|
||||||
# Instalar pnpm globalmente
|
ARG PNPM_VERSION=11.1.3
|
||||||
RUN corepack enable && corepack prepare pnpm@latest --activate
|
RUN corepack enable && corepack prepare pnpm@${PNPM_VERSION} --activate
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
@@ -32,13 +35,18 @@ COPY --from=deps /app/node_modules ./node_modules
|
|||||||
# Copiar todo o código fonte
|
# Copiar todo o código fonte
|
||||||
COPY . .
|
COPY . .
|
||||||
|
|
||||||
|
# Garantir que o pdf.worker vem da versão instalada no stage 1, não do host
|
||||||
|
COPY --from=deps /app/public/pdf.worker.min.mjs ./public/pdf.worker.min.mjs
|
||||||
|
|
||||||
# Variáveis de ambiente necessárias para o build
|
# Variáveis de ambiente necessárias para o build
|
||||||
# DATABASE_URL será fornecida em runtime, mas precisa estar definida para validação
|
|
||||||
ENV NEXT_TELEMETRY_DISABLED=1 \
|
ENV NEXT_TELEMETRY_DISABLED=1 \
|
||||||
NODE_ENV=production
|
NODE_ENV=production
|
||||||
|
|
||||||
|
# Nota: a integração Logo.dev não precisa mais de build args. O token
|
||||||
|
# `LOGO_DEV_TOKEN` é lido em runtime no servidor — basta configurá-lo no
|
||||||
|
# host (Coolify, Railway, etc.) junto com `LOGO_DEV_SECRET_KEY`.
|
||||||
|
|
||||||
# Build da aplicação Next.js
|
# Build da aplicação Next.js
|
||||||
# Nota: Se houver erros de tipo, ajuste typescript.ignoreBuildErrors no next.config.ts
|
|
||||||
RUN pnpm build
|
RUN pnpm build
|
||||||
|
|
||||||
# ============================================
|
# ============================================
|
||||||
@@ -46,8 +54,8 @@ RUN pnpm build
|
|||||||
# ============================================
|
# ============================================
|
||||||
FROM node:22-alpine AS runner
|
FROM node:22-alpine AS runner
|
||||||
|
|
||||||
# Instalar pnpm globalmente
|
ARG PNPM_VERSION=11.1.3
|
||||||
RUN corepack enable && corepack prepare pnpm@latest --activate
|
RUN corepack enable && corepack prepare pnpm@${PNPM_VERSION} --activate
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
@@ -55,12 +63,27 @@ WORKDIR /app
|
|||||||
RUN addgroup --system --gid 1001 nodejs && \
|
RUN addgroup --system --gid 1001 nodejs && \
|
||||||
adduser --system --uid 1001 nextjs
|
adduser --system --uid 1001 nextjs
|
||||||
|
|
||||||
# Copiar apenas arquivos necessários para produção
|
# Instalar deps do drizzle-kit em diretório separado ANTES de copiar o standalone
|
||||||
COPY --from=builder /app/public ./public
|
# Isso evita que o pnpm install sobrescreva o node_modules do Next.js standalone
|
||||||
COPY --from=builder /app/package.json ./package.json
|
COPY --from=builder /app/package.json /tmp/pkg.json
|
||||||
COPY --from=builder /app/pnpm-lock.yaml ./pnpm-lock.yaml
|
RUN mkdir -p /app/migrate && \
|
||||||
|
node -e "\
|
||||||
|
const p=JSON.parse(require('fs').readFileSync('/tmp/pkg.json','utf8'));\
|
||||||
|
require('fs').writeFileSync('/app/migrate/package.json',JSON.stringify({\
|
||||||
|
name:'openmonetis-migrate',version:p.version,\
|
||||||
|
dependencies:{\
|
||||||
|
'drizzle-orm':p.dependencies['drizzle-orm'],\
|
||||||
|
'pg':p.dependencies['pg']\
|
||||||
|
},\
|
||||||
|
devDependencies:{'drizzle-kit':p.devDependencies['drizzle-kit']}\
|
||||||
|
}));" && \
|
||||||
|
cd /app/migrate && pnpm install --no-frozen-lockfile --ignore-scripts && \
|
||||||
|
chown -R nextjs:nodejs /app/migrate
|
||||||
|
|
||||||
# Copiar arquivos de build do Next.js
|
# Copiar apenas arquivos necessários para produção
|
||||||
|
COPY --from=builder --chown=nextjs:nodejs /app/public ./public
|
||||||
|
|
||||||
|
# Copiar arquivos de build do Next.js (inclui node_modules standalone com next)
|
||||||
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
|
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
|
||||||
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
|
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
|
||||||
|
|
||||||
@@ -69,8 +92,11 @@ COPY --from=builder --chown=nextjs:nodejs /app/drizzle ./drizzle
|
|||||||
COPY --from=builder --chown=nextjs:nodejs /app/drizzle.config.ts ./drizzle.config.ts
|
COPY --from=builder --chown=nextjs:nodejs /app/drizzle.config.ts ./drizzle.config.ts
|
||||||
COPY --from=builder --chown=nextjs:nodejs /app/src/db ./src/db
|
COPY --from=builder --chown=nextjs:nodejs /app/src/db ./src/db
|
||||||
|
|
||||||
# Copiar node_modules para ter drizzle-kit disponível para migrations
|
# Copiar entrypoint de migrations
|
||||||
COPY --from=builder --chown=nextjs:nodejs /app/node_modules ./node_modules
|
COPY docker-entrypoint.sh ./
|
||||||
|
RUN sed -i 's/\r$//' /app/docker-entrypoint.sh && \
|
||||||
|
chmod +x /app/docker-entrypoint.sh && \
|
||||||
|
chown nextjs:nodejs /app/docker-entrypoint.sh
|
||||||
|
|
||||||
# Definir variáveis de ambiente de produção
|
# Definir variáveis de ambiente de produção
|
||||||
ENV NODE_ENV=production \
|
ENV NODE_ENV=production \
|
||||||
@@ -81,16 +107,13 @@ ENV NODE_ENV=production \
|
|||||||
# Expor porta
|
# Expor porta
|
||||||
EXPOSE 3000
|
EXPOSE 3000
|
||||||
|
|
||||||
# Ajustar permissões para o usuário nextjs
|
|
||||||
RUN chown -R nextjs:nodejs /app
|
|
||||||
|
|
||||||
# Mudar para usuário não-root
|
# Mudar para usuário não-root
|
||||||
USER nextjs
|
USER nextjs
|
||||||
|
|
||||||
# Health check
|
# Health check
|
||||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
|
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
|
||||||
CMD node -e "require('http').get('http://localhost:3000/api/health', (r) => {process.exit(r.statusCode === 200 ? 0 : 1)})" || exit 1
|
CMD wget --quiet --tries=1 --spider http://127.0.0.1:3000/api/health || exit 1
|
||||||
|
|
||||||
# Comando de inicialização
|
# Entrypoint: roda migrations e depois executa o CMD
|
||||||
# Nota: Em produção com standalone build, o servidor é iniciado pelo arquivo server.js
|
ENTRYPOINT ["/app/docker-entrypoint.sh"]
|
||||||
CMD ["node", "server.js"]
|
CMD ["node", "server.js"]
|
||||||
|
|||||||
453
README.md
@@ -1,14 +1,16 @@
|
|||||||
<p align="center">
|
<p align="center">
|
||||||
<img src="./public/images/logo_small.png" alt="OpenMonetis Logo" height="80" />
|
<img src="./public/images/logo_small.svg" alt="OpenMonetis Logo" height="80" />
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
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/)
|
||||||
@@ -20,7 +22,7 @@
|
|||||||
---
|
---
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<img src="./public/images/dashboard-preview-light.webp" alt="Dashboard Preview" width="800" />
|
<img src="./public/images/dashboard-preview-light.png" alt="Dashboard Preview" width="800" />
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -28,15 +30,19 @@
|
|||||||
## 📖 Índice
|
## 📖 Índice
|
||||||
|
|
||||||
- [Sobre o Projeto](#-sobre-o-projeto)
|
- [Sobre o Projeto](#-sobre-o-projeto)
|
||||||
- [Instalação via Script](#-instalação-via-script)
|
- [Como rodar o OpenMonetis](#-como-rodar-o-openmonetis)
|
||||||
- [Início Rápido (manual)](#-início-rápido)
|
- [Perfil 1 — Usar](#perfil-1--usar-self-hosting)
|
||||||
|
- [Perfil 2 — Desenvolver](#perfil-2--desenvolver)
|
||||||
- [Scripts Disponíveis](#-scripts-disponíveis)
|
- [Scripts Disponíveis](#-scripts-disponíveis)
|
||||||
- [Docker](#-docker)
|
- [Docker](#-docker)
|
||||||
|
- [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)
|
||||||
|
- [Star History](#-star-history)
|
||||||
- [Licença](#-licença)
|
- [Licença](#-licença)
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -53,33 +59,37 @@ A ideia é simples: ter um lugar onde consigo ver todas as minhas contas, cartõ
|
|||||||
|
|
||||||
**1. Não há versão hospedada online** — Este projeto é self-hosted. Você precisa rodar no seu próprio computador ou servidor.
|
**1. Não há versão hospedada online** — Este projeto é self-hosted. Você precisa rodar no seu próprio computador ou servidor.
|
||||||
|
|
||||||
**2. Não há Open Finance** — Não há conexão automática com bancos. Você pode registrar transações manualmente ou importar extratos nos formatos OFX e XLS/XLSX.
|
**2. Não há Open Finance** — Não há conexão automática com bancos. Você pode registrar transações manualmente, usar o app companion para capturar notificações bancárias ou importar extratos nos formatos OFX e XLS/XLSX.
|
||||||
|
|
||||||
**3. Requer disciplina** — O OpenMonetis funciona melhor para quem tem disciplina de registrar os gastos regularmente, quer controle total sobre seus dados e gosta de entender exatamente onde o dinheiro está indo.
|
**3. Requer disciplina** — O OpenMonetis funciona melhor para quem tem disciplina de registrar os gastos regularmente, quer controle total sobre seus dados e gosta de entender exatamente onde o dinheiro está indo.
|
||||||
|
|
||||||
### Funcionalidades
|
### Funcionalidades
|
||||||
|
|
||||||
💰 **Contas e transações** — Contas bancárias, cartões, dinheiro. Receitas, despesas e transferências. Categorização, 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.
|
||||||
|
|
||||||
💸 **Parcelamentos avançados** — Séries de parcelas, antecipação com cálculo de desconto, análise consolidada.
|
💸 **Parcelamentos avançados** — Séries de parcelas, antecipação com cálculo de desconto, análise consolidada.
|
||||||
|
|
||||||
🤖 **Insights com IA** — Análises geradas por Claude, GPT, Gemini ou OpenRouter. Insights personalizados e histórico salvo.
|
🤖 **Insights com IA** — Análises geradas por Claude, GPT, Gemini, MiniMax, OpenRouter ou modelos locais via Ollama. Insights personalizados e histórico salvo.
|
||||||
|
|
||||||
👥 **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.
|
||||||
|
|
||||||
📲 **OpenMonetis Companion** — App Android que captura notificações bancárias (Nubank, Itaú, Bradesco, Inter, C6 e outros) e envia como pré-lançamentos para revisão. [Repositório](https://github.com/felipegcoutinho/openmonetis-companion).
|
📲 **OpenMonetis Companion** — App Android que captura notificações bancárias (Nubank, Itaú, Bradesco, Inter, C6 e outros) e envia automaticamente como pré-lançamentos para revisão — sem digitar nada. [Repositório](https://github.com/felipegcoutinho/openmonetis-companion).
|
||||||
|
|
||||||
⚙️ **Personalização** — Tema dark/light e modo privacidade.
|
<p align="center">
|
||||||
|
<img src="./public/images/companion-preview-light.webp" alt="OpenMonetis Companion" width="300" height="600" />
|
||||||
|
</p>
|
||||||
|
|
||||||
|
⚙️ **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
|
||||||
|
|
||||||
@@ -87,88 +97,126 @@ 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, OpenRouter)
|
- **Vercel AI SDK** (Claude, GPT, Gemini, MiniMax, OpenRouter, Ollama)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## ⚡ Instalação via Script
|
## 🚀 Como rodar o OpenMonetis
|
||||||
|
|
||||||
A forma mais rápida de instalar. O script verifica dependências, configura o `.env` interativamente e sobe o banco automaticamente.
|
Escolha o perfil que corresponde ao seu objetivo:
|
||||||
|
|
||||||
**Pré-requisito:** Node.js 22+
|
| | Perfil 1 — Usar | Perfil 2 — Desenvolver |
|
||||||
|
|---|---|---|
|
||||||
|
| **Objetivo** | Rodar o app pronto | Modificar o código |
|
||||||
|
| **Clonar repositório** | Não | Sim |
|
||||||
|
| **Node.js / pnpm** | Não | Sim (Node 22+) |
|
||||||
|
| **Docker** | Sim | Sim |
|
||||||
|
| **Como iniciar** | `docker compose up -d` | `pnpm docker:db` + `pnpm dev` |
|
||||||
|
| **App roda em** | Container Docker | Host local (hot-reload) |
|
||||||
|
| **Banco roda em** | Container Docker | Container Docker |
|
||||||
|
| **`DATABASE_URL` (host)** | `db` (automático pelo compose) | `localhost` |
|
||||||
|
| **Banco remoto (Supabase, Neon...)** | Sim (`docker compose up -d app`) | Sim (ajustar `DATABASE_URL`) |
|
||||||
|
| **Como atualizar** | `pnpm docker:update` | `git pull` + `pnpm install` + `pnpm db:push` |
|
||||||
|
| **Indicado para** | Self-hosting, VPS, servidor | Contribuidores, customizações |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Perfil 1 — Usar (self-hosting)
|
||||||
|
|
||||||
|
Só quer rodar o OpenMonetis. **Não precisa clonar o repositório nem instalar Node.js** — apenas Docker.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Mac / Linux / WSL
|
# 1. Baixe o compose
|
||||||
curl -fsSL https://raw.githubusercontent.com/felipegcoutinho/openmonetis/main/setup.mjs -o setup.mjs && node setup.mjs
|
curl -fsSL https://raw.githubusercontent.com/felipegcoutinho/openmonetis/main/docker-compose.yml -o docker-compose.yml
|
||||||
|
|
||||||
# Windows (PowerShell)
|
# 2. Crie um .env na mesma pasta.
|
||||||
curl -o setup.mjs https://raw.githubusercontent.com/felipegcoutinho/openmonetis/main/setup.mjs ; node setup.mjs
|
# .env mínimo recomendado para produção
|
||||||
|
BETTER_AUTH_SECRET=gere-um-valor-com-openssl-rand-base64-32
|
||||||
|
BETTER_AUTH_URL=http://seu-dominio.com
|
||||||
|
DISABLE_SIGNUP=false # opcional: true bloqueia novos cadastros
|
||||||
|
|
||||||
|
# 3. Suba tudo
|
||||||
|
docker compose up -d
|
||||||
```
|
```
|
||||||
|
|
||||||
O script irá:
|
Acesse em: `http://localhost:3000`
|
||||||
- Verificar Node, pnpm, Git e Docker
|
|
||||||
- Perguntar se quer banco local (Docker) ou remoto (Supabase, Neon, etc.)
|
O banco sobe com credenciais padrão. Para personalizar (senha, Google OAuth, e-mail, IA...), crie um `.env` na mesma pasta **antes** de subir.
|
||||||
- Gerar o `BETTER_AUTH_SECRET` automaticamente
|
|
||||||
- Configurar opcionais: Google OAuth, e-mail, IA, domínio público
|
Mais sobre .env em [Variáveis de Ambiente](#-variáveis-de-ambiente).
|
||||||
- Clonar o repositório, instalar dependências e aplicar o schema
|
|
||||||
|
**Banco remoto (Supabase, Neon, Railway...):** defina `DATABASE_URL` no `.env` e suba só o app:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose up -d app
|
||||||
|
```
|
||||||
|
|
||||||
|
**Não tem Docker instalado?** Em servidores Ubuntu 24.04 limpos, use o script de instalação:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -fsSL https://raw.githubusercontent.com/felipegcoutinho/openmonetis/main/scripts/install-deps.sh -o install-deps.sh
|
||||||
|
sudo sh install-deps.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
> Ao final, faça **logout e login** para as permissões do grupo `docker` terem efeito.
|
||||||
|
|
||||||
|
#### Atualizando (Perfil 1)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pnpm docker:update
|
||||||
|
# ou equivalente:
|
||||||
|
docker compose pull && docker compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
O schema do banco é aplicado automaticamente no startup — nenhum passo extra necessário.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🚀 Início Rápido (manual)
|
### Perfil 2 — Desenvolver
|
||||||
|
|
||||||
### Pré-requisitos
|
Quer modificar o código com hot-reload. O banco roda no Docker, o app roda direto no seu servidor.
|
||||||
|
|
||||||
- Node.js 22+ e pnpm
|
**Requisitos:** Docker + Node.js 22+ + pnpm
|
||||||
- Docker e Docker Compose
|
|
||||||
|
|
||||||
### Passo a Passo
|
```bash
|
||||||
|
# 1. Clone o repositório
|
||||||
|
git clone https://github.com/felipegcoutinho/openmonetis.git
|
||||||
|
cd openmonetis
|
||||||
|
|
||||||
1. **Clone e instale**
|
# 2. Instale as dependências
|
||||||
|
pnpm install
|
||||||
|
|
||||||
```bash
|
# 3. Configure o ambiente
|
||||||
git clone https://github.com/felipegcoutinho/openmonetis.git
|
cp .env.example .env
|
||||||
cd openmonetis
|
# O DATABASE_URL já vem com host "localhost" (correto para dev local).
|
||||||
pnpm install
|
# Edite o .env com suas configurações (BETTER_AUTH_SECRET, etc.)
|
||||||
```
|
|
||||||
|
|
||||||
2. **Configure o `.env`**
|
# 4. Suba o banco
|
||||||
|
pnpm docker:db
|
||||||
|
|
||||||
```bash
|
# 5. Aplique o schema no banco (apenas no primeiro setup)
|
||||||
cp .env.example .env
|
pnpm db:push
|
||||||
```
|
|
||||||
|
|
||||||
Edite o `.env` com suas credenciais. O principal é o `DATABASE_URL` e o `BETTER_AUTH_SECRET`:
|
# 6. Inicie o app com hot-reload
|
||||||
|
pnpm dev
|
||||||
|
```
|
||||||
|
|
||||||
```env
|
Acesse em: `http://localhost:3000`
|
||||||
# Banco local (Docker): use host "localhost"
|
|
||||||
DATABASE_URL=postgresql://openmonetis:openmonetis_dev_password@localhost:5432/openmonetis_db
|
|
||||||
|
|
||||||
# Banco remoto (Supabase, Neon, etc): use a URL completa do provider
|
Toda vez que salvar um arquivo, o app atualiza automaticamente sem precisar reiniciar.
|
||||||
# DATABASE_URL=postgresql://user:password@host:5432/database?sslmode=require
|
|
||||||
|
|
||||||
BETTER_AUTH_SECRET=seu-secret-aqui # gere com: openssl rand -base64 32
|
#### Atualizando (Perfil 2)
|
||||||
BETTER_AUTH_URL=http://localhost:3000
|
|
||||||
```
|
|
||||||
|
|
||||||
3. **Suba o banco de dados** (pule se estiver usando banco remoto)
|
```bash
|
||||||
|
git pull
|
||||||
|
pnpm install # instala dependências novas, se houver
|
||||||
|
pnpm db:push # aplica mudanças de schema, se houver
|
||||||
|
```
|
||||||
|
|
||||||
```bash
|
O `pnpm dev` já em execução detecta as mudanças de código automaticamente — não precisa reiniciar.
|
||||||
docker compose up db -d
|
|
||||||
pnpm db:enableExtensions
|
|
||||||
```
|
|
||||||
|
|
||||||
4. **Execute as migrations e inicie**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
pnpm db:push
|
|
||||||
pnpm dev
|
|
||||||
```
|
|
||||||
|
|
||||||
5. Acesse `http://localhost:3000`
|
|
||||||
|
|
||||||
> **Docker completo** (app + banco em containers): use `pnpm docker:up` ao invés dos passos 3-4.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -196,41 +244,54 @@ pnpm db:studio # Drizzle Studio (UI visual)
|
|||||||
### Utilitários
|
### Utilitários
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pnpm backup # Backup do banco (requer scripts/backup.sh configurado)
|
pnpm backup # Backup completo do banco (ver seção Backup)
|
||||||
```
|
```
|
||||||
|
|
||||||
### Docker
|
### Docker
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pnpm docker:up # Subir app + banco
|
pnpm docker:up # Sobe app (Docker Hub) + banco em background
|
||||||
pnpm docker:up:d # Subir em background
|
pnpm docker:db # Sobe apenas o banco em background (usar com pnpm dev)
|
||||||
pnpm docker:up:db # Subir apenas o banco
|
pnpm docker:down # Para e remove os containers
|
||||||
pnpm docker:down # Parar containers
|
pnpm docker:logs # Logs em tempo real (todos os containers)
|
||||||
pnpm docker:down:volumes # Parar e remover volumes (⚠️ apaga dados!)
|
pnpm docker:update # Atualiza para a imagem mais recente do Hub e reinicia
|
||||||
pnpm docker:logs # Logs em tempo real
|
|
||||||
pnpm docker:restart # Reiniciar
|
|
||||||
pnpm docker:rebuild # Rebuild completo
|
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🐳 Docker
|
## 🐳 Docker
|
||||||
|
|
||||||
O `Dockerfile` usa multi-stage build (deps → builder → runner) com imagem final ~200MB rodando como usuário não-root.
|
O `Dockerfile` usa multi-stage build (deps → builder → runner) com imagem final ~200MB rodando como usuário não-root. Health checks configurados para ambos os serviços (PostgreSQL via `pg_isready`, app via `GET /api/health`).
|
||||||
|
|
||||||
Health checks configurados para ambos os serviços (PostgreSQL via `pg_isready`, app via `GET /api/health`).
|
### Self-hosting (recomendado)
|
||||||
|
|
||||||
|
Baixe apenas o `docker-compose.yml` e suba tudo — sem clonar o repositório, sem instalar dependências:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -fsSL https://raw.githubusercontent.com/felipegcoutinho/openmonetis/main/docker-compose.yml -o docker-compose.yml
|
||||||
|
docker compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
As credenciais padrão do banco já estão configuradas. Para personalizar (senhas, opcionais), crie um `.env` na mesma pasta antes de subir — veja [Variáveis de Ambiente](#-variáveis-de-ambiente).
|
||||||
|
|
||||||
|
### Banco remoto (Supabase, Neon, Railway...)
|
||||||
|
|
||||||
|
Suba apenas o app e aponte para o banco externo via `DATABASE_URL` no `.env`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose up -d app
|
||||||
|
```
|
||||||
|
|
||||||
### Comandos úteis
|
### Comandos úteis
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker compose exec app sh # Shell da aplicação
|
docker compose exec app sh # Shell da aplicação
|
||||||
docker compose exec db psql -U openmonetis -d openmonetis_db # Shell do banco
|
docker compose exec db psql -U openmonetis -d openmonetis_db # Shell do banco
|
||||||
docker compose ps # Status
|
docker compose ps # Status
|
||||||
docker compose exec db pg_dump -U openmonetis openmonetis_db > backup.sql # Backup
|
pnpm backup # Backup (ver seção Backup)
|
||||||
docker compose exec -T db psql -U openmonetis -d openmonetis_db < backup.sql # Restore
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Customizando Portas
|
### Customizando portas
|
||||||
|
|
||||||
```env
|
```env
|
||||||
APP_PORT=3001 # Padrão: 3000
|
APP_PORT=3001 # Padrão: 3000
|
||||||
@@ -239,6 +300,71 @@ DB_PORT=5433 # Padrão: 5432
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## 💾 Backup
|
||||||
|
|
||||||
|
O backup é uma rotina de infraestrutura — não é uma tela no app. Ele opera diretamente sobre o banco PostgreSQL e é executado via linha de comando.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pnpm backup
|
||||||
|
```
|
||||||
|
|
||||||
|
### O que é salvo
|
||||||
|
|
||||||
|
Cada execução gera **3 arquivos** em `backup/`:
|
||||||
|
|
||||||
|
| Arquivo | Conteúdo | Uso |
|
||||||
|
|---|---|---|
|
||||||
|
| `openmonetis_YYYY-MM-DD_HH-MM.dump` | Dump custom dos schemas `public` + `drizzle` | Restore completo via `pg_restore` |
|
||||||
|
| `openmonetis_YYYY-MM-DD_HH-MM.sql.gz` | Dump SQL compactado dos schemas `public` + `drizzle` | Inspeção manual, portabilidade |
|
||||||
|
| `openmonetis_YYYY-MM-DD_HH-MM.data.sql.gz` | Apenas os dados do schema `public` (sem DDL) | Migração parcial, seed de outro ambiente |
|
||||||
|
|
||||||
|
### Modos de conexão
|
||||||
|
|
||||||
|
Configure `DB_MODE` no topo de `scripts/backup.sh`:
|
||||||
|
|
||||||
|
| Modo | Quando usar | Fonte de dados |
|
||||||
|
|---|---|---|
|
||||||
|
| `remote` (padrão) | Banco em Supabase, Neon, Railway, etc. | `DATABASE_URL` do `.env` |
|
||||||
|
| `docker` | Banco no container local | Container `openmonetis_postgres` |
|
||||||
|
|
||||||
|
### Upload para Google Drive (opcional)
|
||||||
|
|
||||||
|
Se o [rclone](https://rclone.org/) estiver instalado e configurado com um remote chamado `gdrive`, os arquivos são enviados automaticamente para `gdrive:BACKUP OPENMONETIS`. Sem o rclone, o backup funciona normalmente e fica apenas local.
|
||||||
|
|
||||||
|
**Retenção:**
|
||||||
|
- Local: 7 dias
|
||||||
|
- Google Drive: 30 dias
|
||||||
|
|
||||||
|
### Automatizar com cron
|
||||||
|
|
||||||
|
Para rodar o backup automaticamente todo dia às 3h:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
crontab -e
|
||||||
|
```
|
||||||
|
|
||||||
|
```cron
|
||||||
|
0 3 * * * cd /caminho/para/openmonetis && pnpm backup >> /var/log/openmonetis-backup.log 2>&1
|
||||||
|
```
|
||||||
|
|
||||||
|
### Restore
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. Zerar o banco
|
||||||
|
docker exec <container-db> psql -U openmonetis -d openmonetis_db \
|
||||||
|
-c "DROP SCHEMA public CASCADE; CREATE SCHEMA public;"
|
||||||
|
|
||||||
|
# 2. Restaurar schema + dados (um comando)
|
||||||
|
docker exec -i <container-db> pg_restore \
|
||||||
|
-U openmonetis -d openmonetis_db \
|
||||||
|
--clean --if-exists --disable-triggers --no-owner --no-privileges \
|
||||||
|
< backup/openmonetis_YYYY-MM-DD_HH-MM.dump
|
||||||
|
```
|
||||||
|
|
||||||
|
> `--disable-triggers` é necessário para evitar erros de FK durante o restore (os dados são inseridos fora de ordem). O usuário `openmonetis` tem permissão para isso.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## ☁️ Storage S3 Compatível
|
## ☁️ Storage S3 Compatível
|
||||||
|
|
||||||
O suporte a anexos de lançamentos usa upload direto com URL pré-assinada. Essa configuração é opcional, mas passa a ser necessária se você quiser habilitar anexos no app.
|
O suporte a anexos de lançamentos usa upload direto com URL pré-assinada. Essa configuração é opcional, mas passa a ser necessária se você quiser habilitar anexos no app.
|
||||||
@@ -256,20 +382,60 @@ S3_BUCKET=
|
|||||||
### Compatibilidade
|
### Compatibilidade
|
||||||
|
|
||||||
- O código atual espera um provider com API compatível com S3 e suporte a `PutObject`, `GetObject`, `HeadObject`, `DeleteObject` e URLs pré-assinadas.
|
- O código atual espera um provider com API compatível com S3 e suporte a `PutObject`, `GetObject`, `HeadObject`, `DeleteObject` e URLs pré-assinadas.
|
||||||
- A implementação usa `endpoint` customizado e `forcePathStyle: true` em [`src/shared/lib/storage/s3-client.ts`](/home/ubuntu/github/openmonetis/src/shared/lib/storage/s3-client.ts).
|
- A implementação usa `endpoint` customizado e `forcePathStyle: true` em [`src/shared/lib/storage/s3-client.ts`](./src/shared/lib/storage/s3-client.ts).
|
||||||
- Em geral isso cobre MinIO, Cloudflare R2, Backblaze B2 S3-Compatible, DigitalOcean Spaces e AWS S3. Mas foi testado apenas no Supabase Storage.
|
- Em geral isso cobre MinIO, Cloudflare R2, Backblaze B2 S3-Compatible, DigitalOcean Spaces e AWS S3. Mas foi testado apenas no Supabase Storage.
|
||||||
- Se o seu provider exigir `virtual-hosted-style` em vez de `path-style`, você vai precisar ajustar essa configuração antes de usar anexos.
|
- Se o seu provider exigir `virtual-hosted-style` em vez de `path-style`, você vai precisar ajustar essa configuração antes de usar anexos.
|
||||||
- Se as variáveis de S3 não forem configuradas, mantenha os anexos desabilitados no seu fluxo de uso.
|
- Se as variáveis de S3 não forem configuradas, mantenha os anexos desabilitados no seu fluxo de uso.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## 🏷️ Logos de Estabelecimentos (Logo.dev)
|
||||||
|
|
||||||
|
O app exibe logos automáticos de marcas na coluna de estabelecimentos nos lançamentos. A integração usa a [Logo.dev](https://www.logo.dev) e é opcional — sem ela, o app exibe as iniciais coloridas normalmente.
|
||||||
|
|
||||||
|
### Variáveis
|
||||||
|
|
||||||
|
```env
|
||||||
|
LOGO_DEV_TOKEN=pk_... # token público (obrigatório para exibir logos)
|
||||||
|
LOGO_DEV_SECRET_KEY=sk_... # chave secreta (obrigatório para o picker de busca)
|
||||||
|
```
|
||||||
|
|
||||||
|
> **Atualizando da v2.4.1 ou anterior:** a variável foi renomeada de `NEXT_PUBLIC_LOGO_DEV_TOKEN` para `LOGO_DEV_TOKEN`. Renomeie no seu `.env` (ou nas variáveis do Coolify/host) e remova o secret homônimo do GitHub Actions — ele não é mais usado. Não há outra etapa de migração.
|
||||||
|
|
||||||
|
### Como configurar
|
||||||
|
|
||||||
|
Ambas as variáveis são lidas em **runtime** pelo servidor Next.js. Não há mais nenhuma etapa no CI nem `--build-arg` no Docker.
|
||||||
|
|
||||||
|
**Self-hosted via Docker Hub (Coolify, Railway, etc.):**
|
||||||
|
|
||||||
|
1. Adicione `LOGO_DEV_TOKEN` e `LOGO_DEV_SECRET_KEY` nas variáveis de ambiente do host
|
||||||
|
2. Reinicie o container — pronto
|
||||||
|
|
||||||
|
**Desenvolvimento local:**
|
||||||
|
|
||||||
|
Adicione as duas no `.env` e rode `pnpm dev`.
|
||||||
|
|
||||||
|
### Como usar
|
||||||
|
|
||||||
|
Após configurado, passe o mouse sobre o avatar de qualquer estabelecimento nos lançamentos — um ícone de lápis aparece. Clique para abrir o picker, busque pelo nome da marca e selecione o logo desejado. O mapeamento fica salvo por usuário no banco.
|
||||||
|
|
||||||
|
### Arquitetura
|
||||||
|
|
||||||
|
O token **nunca chega ao cliente**. O servidor constrói a URL `https://img.logo.dev/{domain}?token=...` nos endpoints `/api/logo/mapping` e `/api/logo/search`, e o cliente apenas consome a URL pronta. Um Context Provider (`LogoDevProvider`) propaga a flag `enabled` para os componentes que decidem se renderizam o picker.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## 🔐 Variáveis de Ambiente
|
## 🔐 Variáveis de Ambiente
|
||||||
|
|
||||||
Copie `.env.example` para `.env` e configure:
|
**Perfil 2 (dev):** copie `.env.example` para `.env` — o `DATABASE_URL` já vem com `localhost`, pronto para uso com `pnpm dev`.
|
||||||
|
|
||||||
|
**Perfil 1 (Docker):** não precisa definir `DATABASE_URL` — o compose já configura automaticamente com host `db`. Só defina se usar banco remoto (Supabase, Neon, etc.).
|
||||||
|
|
||||||
### Obrigatórias
|
### Obrigatórias
|
||||||
|
|
||||||
```env
|
```env
|
||||||
|
# Perfil 2 (dev): host "localhost" — o banco roda em container, o app no host
|
||||||
|
# Perfil 1 (Docker): não precisa definir — o compose usa "db" automaticamente
|
||||||
DATABASE_URL=postgresql://openmonetis:openmonetis_dev_password@localhost:5432/openmonetis_db
|
DATABASE_URL=postgresql://openmonetis:openmonetis_dev_password@localhost:5432/openmonetis_db
|
||||||
BETTER_AUTH_SECRET=seu-secret-aqui # openssl rand -base64 32
|
BETTER_AUTH_SECRET=seu-secret-aqui # openssl rand -base64 32
|
||||||
BETTER_AUTH_URL=http://localhost:3000
|
BETTER_AUTH_URL=http://localhost:3000
|
||||||
@@ -283,6 +449,12 @@ POSTGRES_USER=openmonetis
|
|||||||
POSTGRES_PASSWORD=openmonetis_dev_password
|
POSTGRES_PASSWORD=openmonetis_dev_password
|
||||||
POSTGRES_DB=openmonetis_db
|
POSTGRES_DB=openmonetis_db
|
||||||
|
|
||||||
|
# Autenticação
|
||||||
|
DISABLE_SIGNUP=false # true bloqueia novos cadastros
|
||||||
|
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
|
||||||
|
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=
|
||||||
S3_REGION=
|
S3_REGION=
|
||||||
@@ -305,9 +477,62 @@ RESEND_FROM_EMAIL=
|
|||||||
ANTHROPIC_API_KEY=
|
ANTHROPIC_API_KEY=
|
||||||
OPENAI_API_KEY=
|
OPENAI_API_KEY=
|
||||||
GOOGLE_GENERATIVE_AI_API_KEY=
|
GOOGLE_GENERATIVE_AI_API_KEY=
|
||||||
|
MINIMAX_API_KEY=
|
||||||
OPENROUTER_API_KEY=
|
OPENROUTER_API_KEY=
|
||||||
|
OLLAMA_BASE_URL=http://localhost:11434/v1
|
||||||
|
OLLAMA_API_KEY=
|
||||||
|
|
||||||
|
# Logo.dev (opcional, necessário para logos automáticos de estabelecimentos)
|
||||||
|
# Ambas as variáveis são runtime — basta definir no host; nenhum build arg necessário.
|
||||||
|
LOGO_DEV_TOKEN=
|
||||||
|
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
|
||||||
|
|
||||||
|
O provider Ollama permite gerar insights usando modelos locais. Instale e suba o Ollama no host onde o modelo ficará disponível:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ollama pull llama3.2
|
||||||
|
ollama serve
|
||||||
|
```
|
||||||
|
|
||||||
|
Configure a URL OpenAI-compatible no `.env`:
|
||||||
|
|
||||||
|
```env
|
||||||
|
OLLAMA_BASE_URL=http://localhost:11434/v1
|
||||||
|
# Opcional; normalmente o Ollama local não exige chave.
|
||||||
|
OLLAMA_API_KEY=
|
||||||
|
```
|
||||||
|
|
||||||
|
Se o OpenMonetis estiver rodando dentro de um container Docker e o Ollama estiver no host, `localhost` aponta para o próprio container. Nesse caso, use uma URL acessível a partir do container, como `http://host.docker.internal:11434/v1` quando disponível, ou o endereço da rede Docker/host configurado no seu ambiente.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🎨 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
|
||||||
@@ -342,7 +567,18 @@ openmonetis/
|
|||||||
│ │ └── auth/ # Formulários de autenticação
|
│ │ └── auth/ # Formulários de autenticação
|
||||||
│ │
|
│ │
|
||||||
│ ├── shared/ # Código reutilizado entre features
|
│ ├── shared/ # Código reutilizado entre features
|
||||||
│ │ ├── components/ # UI compartilhada (shadcn/ui, navigation, skeletons...)
|
│ │ ├── components/ # UI compartilhada
|
||||||
|
│ │ │ ├── ui/ # shadcn/ui primitives
|
||||||
|
│ │ │ ├── navigation/ # navbar, sidebar, breadcrumbs
|
||||||
|
│ │ │ ├── brand/ # logos do app
|
||||||
|
│ │ │ ├── widgets/ # widget-card e variantes
|
||||||
|
│ │ │ ├── feedback/ # empty-state, status-dot, payment-success
|
||||||
|
│ │ │ ├── entity-avatar/ # avatares de categoria/estabelecimento
|
||||||
|
│ │ │ ├── month-picker/ # seletor de período
|
||||||
|
│ │ │ ├── logo-picker/ # seletor de logos
|
||||||
|
│ │ │ ├── calculator/ # calculadora de cálculos rápidos
|
||||||
|
│ │ │ ├── skeletons/ # loading skeletons
|
||||||
|
│ │ │ └── providers/ # React context providers
|
||||||
│ │ ├── hooks/ # React hooks globais
|
│ │ ├── hooks/ # React hooks globais
|
||||||
│ │ ├── lib/ # Helpers de domínio (auth, db, payers, schemas, email...)
|
│ │ ├── lib/ # Helpers de domínio (auth, db, payers, schemas, email...)
|
||||||
│ │ └── utils/ # Utilitários (currency, date, period, math, string...)
|
│ │ └── utils/ # Utilitários (currency, date, period, math, string...)
|
||||||
@@ -358,6 +594,22 @@ openmonetis/
|
|||||||
└── proxy.ts # Middleware (auth + multi-domínio)
|
└── proxy.ts # Middleware (auth + multi-domínio)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Estrutura interna de uma feature
|
||||||
|
|
||||||
|
Toda feature em `src/features/<nome>/` segue o mesmo padrão:
|
||||||
|
|
||||||
|
```
|
||||||
|
<feature>/
|
||||||
|
├── actions.ts # Server Actions (entry point — barrel re-export quando há actions/)
|
||||||
|
├── queries.ts # Funções de leitura do banco (entry point)
|
||||||
|
├── 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
|
||||||
|
```
|
||||||
|
|
||||||
|
A regra é: `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.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🤝 Contribuindo
|
## 🤝 Contribuindo
|
||||||
@@ -371,6 +623,17 @@ openmonetis/
|
|||||||
|
|
||||||
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
|
||||||
@@ -383,6 +646,18 @@ Outras formas de contribuir: ⭐ estrela no repo, reportar bugs, melhorar docs,
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## ⭐ Star History
|
||||||
|
|
||||||
|
<a href="https://www.star-history.com/?repos=felipegcoutinho%2Fopenmonetis&type=date&legend=top-left">
|
||||||
|
<picture>
|
||||||
|
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=felipegcoutinho/openmonetis&type=date&theme=dark&legend=top-left" />
|
||||||
|
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=felipegcoutinho/openmonetis&type=date&legend=top-left" />
|
||||||
|
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=felipegcoutinho/openmonetis&type=date&legend=top-left" />
|
||||||
|
</picture>
|
||||||
|
</a>
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## 📄 Licença
|
## 📄 Licença
|
||||||
|
|
||||||
**Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International** (CC BY-NC-SA 4.0).
|
**Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International** (CC BY-NC-SA 4.0).
|
||||||
@@ -397,12 +672,6 @@ Para o texto legal completo, consulte o arquivo [LICENSE](LICENSE) ou visite [cr
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🙏 Agradecimentos
|
|
||||||
|
|
||||||
[Next.js](https://nextjs.org/) · [Better Auth](https://better-auth.com/) · [Drizzle ORM](https://orm.drizzle.team/) · [shadcn/ui](https://ui.shadcn.com/) · [Biome](https://biomejs.dev/) · [Vercel](https://vercel.com/)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
**Desenvolvido por:** Felipe Coutinho — [@felipegcoutinho](https://github.com/felipegcoutinho)
|
**Desenvolvido por:** Felipe Coutinho — [@felipegcoutinho](https://github.com/felipegcoutinho)
|
||||||
|
|
||||||
<div align="center">
|
<div align="center">
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://biomejs.dev/schemas/2.4.8/schema.json",
|
"$schema": "https://biomejs.dev/schemas/2.4.16/schema.json",
|
||||||
"vcs": {
|
"vcs": {
|
||||||
"enabled": true,
|
"enabled": true,
|
||||||
"clientKind": "git",
|
"clientKind": "git",
|
||||||
|
|||||||
@@ -1,138 +1,53 @@
|
|||||||
# Docker Compose para Next.js + PostgreSQL
|
|
||||||
name: openmonetis
|
name: openmonetis
|
||||||
|
|
||||||
# MODOS DE USO:
|
|
||||||
# 1. Banco LOCAL (PostgreSQL em container):
|
|
||||||
# - Configure DATABASE_URL com host "db" no .env
|
|
||||||
# - Execute: docker compose up
|
|
||||||
#
|
|
||||||
# 2. Banco REMOTO (ex: Supabase, Neon, etc):
|
|
||||||
# - Configure DATABASE_URL com a URL do banco remoto no .env
|
|
||||||
# - Execute: docker compose up app (apenas o serviço app)
|
|
||||||
#
|
|
||||||
# 3. Para parar todos os serviços:
|
|
||||||
# - Execute: docker compose down
|
|
||||||
#
|
|
||||||
# 4. Para remover volumes (CUIDADO: apaga dados do banco local):
|
|
||||||
# - Execute: docker compose down -v
|
|
||||||
|
|
||||||
services:
|
services:
|
||||||
# ============================================
|
|
||||||
# Serviço: PostgreSQL (Banco de dados local)
|
|
||||||
# ============================================
|
|
||||||
db:
|
db:
|
||||||
image: postgres:18-alpine
|
image: postgres:18-alpine
|
||||||
container_name: openmonetis_postgres
|
container_name: openmonetis_postgres
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|
||||||
environment:
|
environment:
|
||||||
POSTGRES_USER: ${POSTGRES_USER:-openmonetis}
|
POSTGRES_USER: ${POSTGRES_USER:-openmonetis}
|
||||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-openmonetis_dev_password}
|
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-openmonetis_dev_password}
|
||||||
POSTGRES_DB: ${POSTGRES_DB:-openmonetis_db}
|
POSTGRES_DB: ${POSTGRES_DB:-openmonetis_db}
|
||||||
PGDATA: /var/lib/postgresql/data
|
|
||||||
POSTGRES_INITDB_ARGS: "-E UTF8 --locale=C"
|
POSTGRES_INITDB_ARGS: "-E UTF8 --locale=C"
|
||||||
|
PGDATA: /var/lib/postgresql/data
|
||||||
ports:
|
ports:
|
||||||
- "${DB_PORT:-5432}:5432"
|
- "${DB_PORT:-5432}:5432"
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
- postgres_data:/var/lib/postgresql/data
|
- postgres_data:/var/lib/postgresql/data
|
||||||
|
|
||||||
# Cria extensão pgcrypto inline (necessária para gen_random_bytes no schema)
|
|
||||||
entrypoint: ["/bin/sh", "-c"]
|
|
||||||
command:
|
|
||||||
- |
|
|
||||||
echo 'CREATE EXTENSION IF NOT EXISTS pgcrypto;' > /docker-entrypoint-initdb.d/init.sql
|
|
||||||
exec docker-entrypoint.sh postgres
|
|
||||||
|
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test:
|
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-openmonetis} -d ${POSTGRES_DB:-openmonetis_db}"]
|
||||||
[
|
|
||||||
"CMD-SHELL",
|
|
||||||
"pg_isready -U ${POSTGRES_USER:-openmonetis} -d ${POSTGRES_DB:-openmonetis_db}",
|
|
||||||
]
|
|
||||||
interval: 10s
|
interval: 10s
|
||||||
timeout: 5s
|
timeout: 5s
|
||||||
retries: 5
|
retries: 5
|
||||||
start_period: 10s
|
start_period: 10s
|
||||||
|
|
||||||
# Para ativar logs de queries (debug), adicione ao command acima:
|
|
||||||
# exec docker-entrypoint.sh postgres -c log_statement=all
|
|
||||||
|
|
||||||
# ============================================
|
|
||||||
# Serviço: Aplicação Next.js
|
|
||||||
# ============================================
|
|
||||||
app:
|
app:
|
||||||
image: felipegcoutinho/openmonetis:latest
|
image: felipegcoutinho/openmonetis:latest
|
||||||
|
|
||||||
container_name: openmonetis_app
|
container_name: openmonetis_app
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|
||||||
ports:
|
ports:
|
||||||
- "${APP_PORT:-3000}:3000"
|
- "${APP_PORT:-3000}:3000"
|
||||||
|
env_file:
|
||||||
|
- path: .env
|
||||||
|
required: false
|
||||||
environment:
|
environment:
|
||||||
NODE_ENV: production
|
NODE_ENV: production
|
||||||
|
DATABASE_URL: ${DATABASE_URL:-postgresql://openmonetis:openmonetis_dev_password@db:5432/openmonetis_db}
|
||||||
# Banco local: use host "db" | Banco remoto: URL completa do provider
|
BETTER_AUTH_SECRET: ${BETTER_AUTH_SECRET:-}
|
||||||
DATABASE_URL: ${DATABASE_URL}
|
|
||||||
|
|
||||||
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:-}
|
||||||
# Email (opcional)
|
|
||||||
RESEND_API_KEY: ${RESEND_API_KEY:-}
|
|
||||||
RESEND_FROM_EMAIL: ${RESEND_FROM_EMAIL:-}
|
|
||||||
|
|
||||||
# OAuth (opcional)
|
|
||||||
GOOGLE_CLIENT_ID: ${GOOGLE_CLIENT_ID:-}
|
|
||||||
GOOGLE_CLIENT_SECRET: ${GOOGLE_CLIENT_SECRET:-}
|
|
||||||
GITHUB_CLIENT_ID: ${GITHUB_CLIENT_ID:-}
|
|
||||||
GITHUB_CLIENT_SECRET: ${GITHUB_CLIENT_SECRET:-}
|
|
||||||
|
|
||||||
# AI providers (opcional)
|
|
||||||
ANTHROPIC_API_KEY: ${ANTHROPIC_API_KEY:-}
|
|
||||||
OPENAI_API_KEY: ${OPENAI_API_KEY:-}
|
|
||||||
GOOGLE_GENERATIVE_AI_API_KEY: ${GOOGLE_GENERATIVE_AI_API_KEY:-}
|
|
||||||
OPENROUTER_API_KEY: ${OPENROUTER_API_KEY:-}
|
|
||||||
|
|
||||||
# Só depende do 'db' se estiver usando banco local
|
|
||||||
# Para banco remoto, comente as linhas abaixo
|
|
||||||
depends_on:
|
depends_on:
|
||||||
db:
|
db:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
|
required: false
|
||||||
# Script de inicialização: roda migrations antes de iniciar o app
|
|
||||||
entrypoint: ["/bin/sh", "-c"]
|
|
||||||
command:
|
|
||||||
- |
|
|
||||||
echo "Aguardando banco de dados..."
|
|
||||||
sleep 5
|
|
||||||
|
|
||||||
echo "Rodando migrations..."
|
|
||||||
pnpm db:push || echo "Migrations falharam ou já estão atualizadas"
|
|
||||||
|
|
||||||
echo "Iniciando aplicação Next.js..."
|
|
||||||
node server.js
|
|
||||||
|
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test:
|
test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://127.0.0.1:3000/api/health"]
|
||||||
[
|
|
||||||
"CMD",
|
|
||||||
"wget",
|
|
||||||
"--quiet",
|
|
||||||
"--tries=1",
|
|
||||||
"--spider",
|
|
||||||
"http://localhost:3000/api/health",
|
|
||||||
]
|
|
||||||
interval: 30s
|
interval: 30s
|
||||||
timeout: 10s
|
timeout: 10s
|
||||||
retries: 3
|
retries: 3
|
||||||
start_period: 40s
|
start_period: 40s
|
||||||
|
|
||||||
# ============================================
|
|
||||||
# Volumes
|
|
||||||
# ============================================
|
|
||||||
volumes:
|
volumes:
|
||||||
postgres_data:
|
postgres_data:
|
||||||
driver: local
|
driver: local
|
||||||
|
|||||||
16
docker-entrypoint.sh
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
|
||||||
|
echo "Rodando migrations..."
|
||||||
|
MIGRATED=0
|
||||||
|
for i in 1 2 3 4 5; do
|
||||||
|
if NODE_PATH=/app/migrate/node_modules /app/migrate/node_modules/.bin/drizzle-kit push; then
|
||||||
|
MIGRATED=1
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
echo "Tentativa $i/5 falhou. Aguardando 5s..."
|
||||||
|
sleep 5
|
||||||
|
done
|
||||||
|
|
||||||
|
[ "$MIGRATED" -eq 0 ] && echo "Aviso: migrations não foram aplicadas."
|
||||||
|
|
||||||
|
exec "$@"
|
||||||
1
drizzle/0024_petite_lucky_pierre.sql
Normal file
@@ -0,0 +1 @@
|
|||||||
|
ALTER TABLE "preferencias_usuario" ADD COLUMN "attachment_max_size_mb" integer DEFAULT 50 NOT NULL;
|
||||||
24
drizzle/0025_burly_colonel_america.sql
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
DROP INDEX "tokens_api_user_id_idx";--> statement-breakpoint
|
||||||
|
DROP INDEX "cartoes_user_id_status_idx";--> statement-breakpoint
|
||||||
|
DROP INDEX "dashboard_notification_states_user_id_archived_idx";--> statement-breakpoint
|
||||||
|
DROP INDEX "contas_user_id_status_idx";--> statement-breakpoint
|
||||||
|
DROP INDEX "antecipacoes_parcelas_series_id_idx";--> statement-breakpoint
|
||||||
|
DROP INDEX "pagadores_user_id_status_idx";--> statement-breakpoint
|
||||||
|
DROP INDEX "pagadores_user_id_role_idx";--> statement-breakpoint
|
||||||
|
CREATE INDEX "account_user_id_idx" ON "account" USING btree ("userId");--> statement-breakpoint
|
||||||
|
CREATE INDEX "anexos_user_id_idx" ON "anexos" USING btree ("user_id");--> statement-breakpoint
|
||||||
|
CREATE INDEX "orcamentos_categoria_id_idx" ON "orcamentos" USING btree ("categoria_id");--> statement-breakpoint
|
||||||
|
CREATE INDEX "cartoes_conta_id_idx" ON "cartoes" USING btree ("conta_id");--> statement-breakpoint
|
||||||
|
CREATE INDEX "import_category_mappings_category_id_idx" ON "import_category_mappings" USING btree ("category_id");--> statement-breakpoint
|
||||||
|
CREATE INDEX "pre_lancamentos_lancamento_id_idx" ON "pre_lancamentos" USING btree ("lancamento_id");--> statement-breakpoint
|
||||||
|
CREATE INDEX "antecipacoes_parcelas_lancamento_id_idx" ON "antecipacoes_parcelas" USING btree ("lancamento_id");--> statement-breakpoint
|
||||||
|
CREATE INDEX "antecipacoes_parcelas_pagador_id_idx" ON "antecipacoes_parcelas" USING btree ("pagador_id");--> statement-breakpoint
|
||||||
|
CREATE INDEX "antecipacoes_parcelas_categoria_id_idx" ON "antecipacoes_parcelas" USING btree ("categoria_id");--> statement-breakpoint
|
||||||
|
CREATE INDEX "anotacoes_user_id_idx" ON "anotacoes" USING btree ("user_id");--> statement-breakpoint
|
||||||
|
CREATE INDEX "passkey_user_id_idx" ON "passkey" USING btree ("userId");--> statement-breakpoint
|
||||||
|
CREATE INDEX "compartilhamentos_pagador_shared_with_user_id_idx" ON "compartilhamentos_pagador" USING btree ("shared_with_user_id");--> statement-breakpoint
|
||||||
|
CREATE INDEX "compartilhamentos_pagador_created_by_user_id_idx" ON "compartilhamentos_pagador" USING btree ("created_by_user_id");--> statement-breakpoint
|
||||||
|
CREATE INDEX "session_user_id_idx" ON "session" USING btree ("userId");--> statement-breakpoint
|
||||||
|
CREATE INDEX "lancamentos_conta_id_idx" ON "lancamentos" USING btree ("conta_id");--> statement-breakpoint
|
||||||
|
CREATE INDEX "lancamentos_categoria_id_idx" ON "lancamentos" USING btree ("categoria_id");--> statement-breakpoint
|
||||||
|
CREATE INDEX "lancamentos_antecipacao_id_idx" ON "lancamentos" USING btree ("antecipacao_id");
|
||||||
2
drizzle/0026_bored_eternity.sql
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
ALTER TABLE "lancamentos" ADD COLUMN "split_group_id" uuid;--> statement-breakpoint
|
||||||
|
CREATE INDEX "lancamentos_user_id_split_group_id_idx" ON "lancamentos" USING btree ("user_id","split_group_id");
|
||||||
1
drizzle/0028_fancy_reaper.sql
Normal file
@@ -0,0 +1 @@
|
|||||||
|
ALTER TABLE "pagadores" ALTER COLUMN "share_code" DROP DEFAULT;
|
||||||
3
drizzle/0029_friendly_spitfire.sql
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
ALTER TABLE "cartoes" ALTER COLUMN "limite" SET DEFAULT '0';--> statement-breakpoint
|
||||||
|
UPDATE "cartoes" SET "limite" = '0' WHERE "limite" IS NULL;--> statement-breakpoint
|
||||||
|
ALTER TABLE "cartoes" ALTER COLUMN "limite" SET NOT NULL;
|
||||||
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;
|
||||||
2711
drizzle/meta/0024_snapshot.json
Normal file
2889
drizzle/meta/0025_snapshot.json
Normal file
2916
drizzle/meta/0026_snapshot.json
Normal file
2915
drizzle/meta/0028_snapshot.json
Normal file
2916
drizzle/meta/0029_snapshot.json
Normal file
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
@@ -169,6 +169,69 @@
|
|||||||
"when": 1774529878374,
|
"when": 1774529878374,
|
||||||
"tag": "0023_sturdy_wolfpack",
|
"tag": "0023_sturdy_wolfpack",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 24,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1774891206703,
|
||||||
|
"tag": "0024_petite_lucky_pierre",
|
||||||
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 25,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1776351838548,
|
||||||
|
"tag": "0025_burly_colonel_america",
|
||||||
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 26,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1777042423451,
|
||||||
|
"tag": "0026_bored_eternity",
|
||||||
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 28,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1777153372633,
|
||||||
|
"tag": "0028_fancy_reaper",
|
||||||
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 29,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1777648189399,
|
||||||
|
"tag": "0029_friendly_spitfire",
|
||||||
|
"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
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
24
knip.jsonc
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://unpkg.com/knip@6/schema-jsonc.json",
|
||||||
|
// Exclude shared UI primitives from dead code reporting while we focus the
|
||||||
|
// cleanup on feature and domain code first.
|
||||||
|
"ignore": [
|
||||||
|
"src/shared/components/ui/**"
|
||||||
|
],
|
||||||
|
// Runtime asset referenced by string in the PDF viewer.
|
||||||
|
"ignoreFiles": [
|
||||||
|
"public/pdf.worker.min.mjs",
|
||||||
|
"setup.mjs"
|
||||||
|
],
|
||||||
|
// PostCSS is inferred from the config file, but the project only depends on
|
||||||
|
// the Tailwind PostCSS plugin directly.
|
||||||
|
// `server-only` is provided implicitly by Next.js — no install needed.
|
||||||
|
"ignoreDependencies": [
|
||||||
|
"postcss",
|
||||||
|
"server-only"
|
||||||
|
],
|
||||||
|
"next": true,
|
||||||
|
"postcss": true,
|
||||||
|
"biome": true,
|
||||||
|
"drizzle": true
|
||||||
|
}
|
||||||
@@ -6,16 +6,24 @@ dotenv.config();
|
|||||||
|
|
||||||
const nextConfig: NextConfig = {
|
const nextConfig: NextConfig = {
|
||||||
output: "standalone",
|
output: "standalone",
|
||||||
experimental: {
|
cacheComponents: true,
|
||||||
turbopackFileSystemCacheForDev: true,
|
|
||||||
},
|
|
||||||
reactCompiler: true,
|
reactCompiler: true,
|
||||||
images: {
|
images: {
|
||||||
remotePatterns: [new URL("https://lh3.googleusercontent.com/**")],
|
remotePatterns: [
|
||||||
|
new URL("https://lh3.googleusercontent.com/**"),
|
||||||
|
{ protocol: "https", hostname: "**" },
|
||||||
|
{ protocol: "http", hostname: "**" },
|
||||||
|
],
|
||||||
},
|
},
|
||||||
devIndicators: {
|
devIndicators: {
|
||||||
position: "bottom-right",
|
position: "bottom-right",
|
||||||
},
|
},
|
||||||
|
experimental: {
|
||||||
|
prefetchInlining: true,
|
||||||
|
turbopackFileSystemCacheForDev: true,
|
||||||
|
optimizePackageImports: ["@remixicon/react"],
|
||||||
|
},
|
||||||
|
|
||||||
// Headers for Safari compatibility
|
// Headers for Safari compatibility
|
||||||
async headers() {
|
async headers() {
|
||||||
return [
|
return [
|
||||||
@@ -39,8 +47,12 @@ const nextConfig: NextConfig = {
|
|||||||
value: "DENY",
|
value: "DENY",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: "Content-Security-Policy",
|
key: "Referrer-Policy",
|
||||||
value: "frame-ancestors 'none';",
|
value: "strict-origin-when-cross-origin",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: "X-Permitted-Cross-Domain-Policies",
|
||||||
|
value: "none",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: "Permissions-Policy",
|
key: "Permissions-Policy",
|
||||||
|
|||||||
106
package.json
@@ -1,57 +1,62 @@
|
|||||||
{
|
{
|
||||||
"name": "openmonetis",
|
"name": "openmonetis",
|
||||||
"version": "2.1.0",
|
"version": "2.7.11",
|
||||||
"private": true,
|
"private": true,
|
||||||
|
"packageManager": "pnpm@11.1.3",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "next dev --turbopack",
|
"dev": "next dev --turbopack",
|
||||||
"dev-env": "tsx scripts/dev.ts",
|
"db:seed": "tsx scripts/mock-data.ts",
|
||||||
"mockup": "tsx scripts/mock-data.ts",
|
|
||||||
"build": "next build",
|
"build": "next build",
|
||||||
"start": "next start",
|
"start": "next start",
|
||||||
"lint": "biome check .",
|
"lint": "biome check .",
|
||||||
|
"lint:deadcode": "knip --reporter compact",
|
||||||
"lint:fix": "biome check --write .",
|
"lint:fix": "biome check --write .",
|
||||||
"env:setup": "bash scripts/setup-env.sh",
|
"env:setup": "node setup.mjs",
|
||||||
"db:generate": "drizzle-kit generate",
|
"db:generate": "drizzle-kit generate",
|
||||||
"db:migrate": "drizzle-kit migrate",
|
"db:migrate": "drizzle-kit migrate",
|
||||||
"db:push": "drizzle-kit push",
|
"db:push": "drizzle-kit push",
|
||||||
"db:enableExtensions": "tsx scripts/postgres/enable-extensions.ts",
|
|
||||||
"db:studio": "drizzle-kit studio",
|
"db:studio": "drizzle-kit studio",
|
||||||
"docker:up": "docker compose up --build",
|
"postinstall": "cp node_modules/pdfjs-dist/build/pdf.worker.min.mjs public/pdf.worker.min.mjs",
|
||||||
"docker:up:db": "docker compose up -d db",
|
"docker:up": "docker compose up -d",
|
||||||
"docker:up:d": "docker compose up --build -d",
|
"//docker:up": "Sobe app (Docker Hub) + banco PostgreSQL em background",
|
||||||
|
"docker:db": "docker compose up -d db",
|
||||||
|
"//docker:db": "Sobe apenas o banco em background (para usar com pnpm dev)",
|
||||||
"docker:down": "docker compose down",
|
"docker:down": "docker compose down",
|
||||||
"docker:down:volumes": "docker compose down -v",
|
"//docker:down": "Para e remove os containers",
|
||||||
"docker:logs": "docker compose logs -f",
|
"docker:logs": "docker compose logs -f",
|
||||||
"docker:logs:app": "docker compose logs -f app",
|
"//docker:logs": "Acompanha logs de todos os containers em tempo real",
|
||||||
"docker:logs:db": "docker compose logs -f db",
|
"docker:update": "docker compose pull && docker compose up -d",
|
||||||
"docker:restart": "docker compose restart",
|
"//docker:update": "Atualiza para a imagem mais recente do Docker Hub e reinicia",
|
||||||
"docker:rebuild": "docker compose up --build --force-recreate",
|
"backup": "bash scripts/backup.sh",
|
||||||
"backup": "bash scripts/backup.sh"
|
"mockup": "tsx scripts/mock-data.ts"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ai-sdk/anthropic": "^3.0.64",
|
"@ai-sdk/anthropic": "^3.0.88",
|
||||||
"@ai-sdk/google": "^3.0.53",
|
"@ai-sdk/google": "^3.0.85",
|
||||||
"@ai-sdk/openai": "^3.0.48",
|
"@ai-sdk/openai": "^3.0.76",
|
||||||
"@aws-sdk/client-s3": "^3.1019.0",
|
"@ai-sdk/openai-compatible": "^2.0.53",
|
||||||
"@aws-sdk/s3-request-presigner": "^3.1019.0",
|
"@aws-sdk/client-s3": "^3.1075.0",
|
||||||
"@better-auth/passkey": "^1.5.6",
|
"@aws-sdk/s3-request-presigner": "^3.1075.0",
|
||||||
|
"@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.3.3",
|
"@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-popover": "^1.1.15",
|
"@radix-ui/react-navigation-menu": "^1.2.16",
|
||||||
|
"@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.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",
|
||||||
@@ -59,47 +64,50 @@
|
|||||||
"@radix-ui/react-toggle-group": "1.1.11",
|
"@radix-ui/react-toggle-group": "1.1.11",
|
||||||
"@radix-ui/react-tooltip": "1.2.8",
|
"@radix-ui/react-tooltip": "1.2.8",
|
||||||
"@remixicon/react": "4.9.0",
|
"@remixicon/react": "4.9.0",
|
||||||
|
"@tanstack/react-query": "^5.101.1",
|
||||||
"@tanstack/react-table": "8.21.3",
|
"@tanstack/react-table": "8.21.3",
|
||||||
"@tanstack/react-virtual": "^3.13.23",
|
"@tanstack/react-virtual": "^3.14.4",
|
||||||
"@vercel/analytics": "^2.0.1",
|
"ai": "^6.0.213",
|
||||||
"@vercel/speed-insights": "^2.0.0",
|
"better-auth": "1.6.22",
|
||||||
"ai": "^6.0.141",
|
|
||||||
"better-auth": "1.5.6",
|
|
||||||
"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.1.0",
|
"date-fns": "^4.4.0",
|
||||||
"drizzle-orm": "0.45.2",
|
"drizzle-orm": "0.45.2",
|
||||||
|
"exceljs": "^4.4.0",
|
||||||
"jspdf": "^4.2.1",
|
"jspdf": "^4.2.1",
|
||||||
"jspdf-autotable": "^5.0.7",
|
"jspdf-autotable": "^5.0.8",
|
||||||
"next": "16.1.7",
|
"next": "16.2.7",
|
||||||
"next-themes": "0.4.6",
|
"next-themes": "0.4.6",
|
||||||
"pg": "8.20.0",
|
"pdfjs-dist": "^6.0.227",
|
||||||
"radix-ui": "^1.4.3",
|
"pg": "8.21.0",
|
||||||
"react": "19.2.4",
|
"react": "19.2.7",
|
||||||
"react-day-picker": "^9.14.0",
|
"react-day-picker": "^10.0.1",
|
||||||
"react-dom": "19.2.4",
|
"react-dom": "19.2.7",
|
||||||
"recharts": "3.8.1",
|
"recharts": "3.8.1",
|
||||||
"resend": "^6.9.4",
|
"resend": "^6.16.0",
|
||||||
"sonner": "2.0.7",
|
"sonner": "2.0.7",
|
||||||
"tailwind-merge": "3.5.0",
|
"tailwind-merge": "3.6.0",
|
||||||
|
"tw-animate-css": "^1.4.0",
|
||||||
"vaul": "1.1.2",
|
"vaul": "1.1.2",
|
||||||
"xlsx": "^0.18.5",
|
"vercel-minimax-ai-provider": "^0.0.2",
|
||||||
"zod": "4.3.6"
|
"zod": "4.4.3"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@biomejs/biome": "2.4.9",
|
"@biomejs/biome": "2.4.16",
|
||||||
"@tailwindcss/postcss": "4.2.2",
|
"@tailwindcss/postcss": "4.3.0",
|
||||||
"@types/canvas-confetti": "^1.9.0",
|
"@types/canvas-confetti": "^1.9.0",
|
||||||
"@types/node": "25.5.0",
|
"@types/node": "25.9.1",
|
||||||
"@types/pg": "^8.20.0",
|
"@types/pg": "^8.20.0",
|
||||||
"@types/react": "19.2.14",
|
"@types/react": "19.2.16",
|
||||||
"@types/react-dom": "19.2.3",
|
"@types/react-dom": "19.2.3",
|
||||||
"dotenv": "^17.3.1",
|
"babel-plugin-react-compiler": "^1.0.0",
|
||||||
|
"dotenv": "^17.4.2",
|
||||||
"drizzle-kit": "0.31.10",
|
"drizzle-kit": "0.31.10",
|
||||||
"tailwindcss": "4.2.2",
|
"knip": "^6.22.0",
|
||||||
"tsx": "4.21.0",
|
"tailwindcss": "4.3.0",
|
||||||
"typescript": "6.0.2"
|
"tsx": "4.22.4",
|
||||||
|
"typescript": "6.0.3"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
7147
pnpm-lock.yaml
generated
@@ -1,5 +1,13 @@
|
|||||||
onlyBuiltDependencies:
|
packages:
|
||||||
- core-js
|
- '.'
|
||||||
- esbuild
|
|
||||||
- sharp
|
allowBuilds:
|
||||||
- unrs-resolver
|
core-js: true
|
||||||
|
esbuild: true
|
||||||
|
sharp: true
|
||||||
|
unrs-resolver: true
|
||||||
|
|
||||||
|
minimumReleaseAge: 0
|
||||||
|
|
||||||
|
overrides:
|
||||||
|
defu: 6.1.7
|
||||||
|
|||||||
4
public/.well-known/security.txt
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
Contact: https://github.com/felipegcoutinho/openmonetis/security/advisories
|
||||||
|
Expires: 2027-04-04T00:00:00.000Z
|
||||||
|
Preferred-Languages: pt-BR, en
|
||||||
|
Canonical: https://openmonetis.com/.well-known/security.txt
|
||||||
|
Before Width: | Height: | Size: 5.4 KiB After Width: | Height: | Size: 3.4 KiB |
@@ -1,15 +1,10 @@
|
|||||||
import localFont from "next/font/local";
|
import { Bricolage_Grotesque } from "next/font/google";
|
||||||
|
|
||||||
export const america = localFont({
|
export const bricolage = Bricolage_Grotesque({
|
||||||
src: [
|
subsets: ["latin"],
|
||||||
{
|
|
||||||
path: "./america-regular.woff2",
|
|
||||||
weight: "400",
|
|
||||||
style: "normal",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
display: "swap",
|
display: "swap",
|
||||||
variable: "--font-america",
|
variable: "--font-bricolage",
|
||||||
|
fallback: ["arial", "ui-sans-serif", "system-ui"],
|
||||||
|
weight: ["500", "600", "700"],
|
||||||
|
preload: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
export const americaFontVariable = america.variable;
|
|
||||||
|
|||||||
BIN
public/images/dashboard-preview-dark.png
Normal file
|
After Width: | Height: | Size: 350 KiB |
|
Before Width: | Height: | Size: 165 KiB |
BIN
public/images/dashboard-preview-light.png
Normal file
|
After Width: | Height: | Size: 355 KiB |
|
Before Width: | Height: | Size: 165 KiB |
|
Before Width: | Height: | Size: 3.2 KiB |
1
public/images/logo_small.svg
Normal file
@@ -0,0 +1 @@
|
|||||||
|
<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>
|
||||||
|
After Width: | Height: | Size: 394 B |
|
Before Width: | Height: | Size: 21 KiB |
1
public/images/logo_text.svg
Normal file
|
After Width: | Height: | Size: 6.7 KiB |
|
Before Width: | Height: | Size: 382 KiB |
|
Before Width: | Height: | Size: 98 KiB |
|
Before Width: | Height: | Size: 98 KiB |
|
Before Width: | Height: | Size: 109 KiB |
|
Before Width: | Height: | Size: 102 KiB |
|
Before Width: | Height: | Size: 134 KiB |
|
Before Width: | Height: | Size: 132 KiB |
|
Before Width: | Height: | Size: 195 KiB |
|
Before Width: | Height: | Size: 189 KiB |
|
Before Width: | Height: | Size: 157 KiB |
|
Before Width: | Height: | Size: 156 KiB |
|
Before Width: | Height: | Size: 108 KiB |
|
Before Width: | Height: | Size: 105 KiB |
|
Before Width: | Height: | Size: 134 KiB |
|
Before Width: | Height: | Size: 132 KiB |
BIN
public/images/pwa-preview-dark.png
Normal file
|
After Width: | Height: | Size: 139 KiB |
|
Before Width: | Height: | Size: 82 KiB |
BIN
public/images/pwa-preview-light.png
Normal file
|
After Width: | Height: | Size: 137 KiB |
|
Before Width: | Height: | Size: 84 KiB |
37
public/llms.txt
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
# OpenMonetis
|
||||||
|
|
||||||
|
> OpenMonetis is a self-hosted personal finance web app for manual financial control. It helps users manage accounts, cards, invoices, budgets, notes, reports, attachments, and AI-generated insights. The product UI is in Brazilian Portuguese, the codebase uses English folder and import names, and there is no hosted SaaS version.
|
||||||
|
>
|
||||||
|
> **Stack:** Next.js 16, React 19, PostgreSQL, Drizzle ORM, Better Auth, Tailwind CSS 4, shadcn/ui. Package manager: pnpm. Linter: Biome.
|
||||||
|
|
||||||
|
OpenMonetis is meant to be deployed by the user on their own machine or server.
|
||||||
|
There is no Open Finance or automatic bank synchronization.
|
||||||
|
Transactions can be entered manually or imported from OFX and XLS/XLSX files.
|
||||||
|
Attachments are optional and require S3-compatible storage.
|
||||||
|
The public website is mainly a landing page; the main technical documentation lives in the GitHub repository.
|
||||||
|
|
||||||
|
## Docs
|
||||||
|
|
||||||
|
- [Landing page](/): Public homepage and high-level product overview
|
||||||
|
- [README](https://github.com/felipegcoutinho/openmonetis/blob/main/README.md): Main project documentation covering features, installation, Docker, environment variables, architecture, contributing, and license
|
||||||
|
- [CHANGELOG](https://github.com/felipegcoutinho/openmonetis/blob/main/CHANGELOG.md): Release history and notable changes
|
||||||
|
- [LICENSE](https://github.com/felipegcoutinho/openmonetis/blob/main/LICENSE): CC BY-NC-SA 4.0 license terms
|
||||||
|
|
||||||
|
## Setup
|
||||||
|
|
||||||
|
- [Setup script](https://raw.githubusercontent.com/felipegcoutinho/openmonetis/main/setup.mjs): Interactive installer for local or self-hosted setup
|
||||||
|
- [Environment example](https://github.com/felipegcoutinho/openmonetis/blob/main/.env.example): Required and optional environment variables
|
||||||
|
- [Docker Compose](https://github.com/felipegcoutinho/openmonetis/blob/main/docker-compose.yml): Local app and PostgreSQL stack definition
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
- [CLAUDE.md](https://github.com/felipegcoutinho/openmonetis/blob/main/CLAUDE.md): Project architecture, naming rules, query rules, and feature checklist
|
||||||
|
|
||||||
|
## Optional
|
||||||
|
|
||||||
|
- [robots.txt](/robots.txt): Crawl policy for the public site
|
||||||
|
|
||||||
|
## Related Projects
|
||||||
|
|
||||||
|
- [OpenMonetis Companion](https://github.com/felipegcoutinho/openmonetis-companion): Android app that captures bank notifications and sends them to the OpenMonetis inbox for review
|
||||||
|
|
||||||
BIN
public/logos/bipa.png
Normal file
|
After Width: | Height: | Size: 34 KiB |
BIN
public/logos/dinheiro.png
Normal file
|
After Width: | Height: | Size: 17 KiB |
29
public/pdf.worker.min.mjs
Normal file
1
public/providers/minimax.svg
Normal file
@@ -0,0 +1 @@
|
|||||||
|
<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>
|
||||||
|
After Width: | Height: | Size: 1.5 KiB |
1
public/providers/ollama_dark.svg
Normal file
|
After Width: | Height: | Size: 8.4 KiB |
1
public/providers/ollama_light.svg
Normal file
|
After Width: | Height: | Size: 8.4 KiB |
@@ -58,21 +58,26 @@ DATA_FILE="$BACKUP_DIR/openmonetis_${TIMESTAMP}.data.sql.gz"
|
|||||||
|
|
||||||
log "Iniciando backup (modo: $DB_MODE)..."
|
log "Iniciando backup (modo: $DB_MODE)..."
|
||||||
|
|
||||||
|
# Schemas relevantes do OpenMonetis (descarta lixo Supabase: auth, realtime, storage, vault, graphql, etc.)
|
||||||
|
SCHEMA_FLAGS=(--schema=public --schema=drizzle)
|
||||||
|
|
||||||
# --- Dump ---
|
# --- Dump ---
|
||||||
if [[ "$DB_MODE" == "remote" ]]; then
|
if [[ "$DB_MODE" == "remote" ]]; then
|
||||||
# --no-owner --no-privileges: necessário no Supabase (roles gerenciados internamente)
|
# --no-owner --no-privileges: necessário no Supabase (roles gerenciados internamente)
|
||||||
pg_dump --format=custom --no-owner --no-privileges \
|
pg_dump --format=custom --no-owner --no-privileges \
|
||||||
|
"${SCHEMA_FLAGS[@]}" \
|
||||||
"$REMOTE_DB_URL" > "$DUMP_FILE"
|
"$REMOTE_DB_URL" > "$DUMP_FILE"
|
||||||
|
|
||||||
pg_dump --no-owner --no-privileges \
|
pg_dump --no-owner --no-privileges \
|
||||||
|
"${SCHEMA_FLAGS[@]}" \
|
||||||
"$REMOTE_DB_URL" | gzip > "$SQL_FILE"
|
"$REMOTE_DB_URL" | gzip > "$SQL_FILE"
|
||||||
|
|
||||||
elif [[ "$DB_MODE" == "docker" ]]; then
|
elif [[ "$DB_MODE" == "docker" ]]; then
|
||||||
docker exec "$DOCKER_CONTAINER" pg_dump \
|
docker exec "$DOCKER_CONTAINER" pg_dump \
|
||||||
-U "$DOCKER_DB_USER" -Fc "$DOCKER_DB_NAME" > "$DUMP_FILE"
|
-U "$DOCKER_DB_USER" -Fc "${SCHEMA_FLAGS[@]}" "$DOCKER_DB_NAME" > "$DUMP_FILE"
|
||||||
|
|
||||||
docker exec "$DOCKER_CONTAINER" pg_dump \
|
docker exec "$DOCKER_CONTAINER" pg_dump \
|
||||||
-U "$DOCKER_DB_USER" "$DOCKER_DB_NAME" | gzip > "$SQL_FILE"
|
-U "$DOCKER_DB_USER" "${SCHEMA_FLAGS[@]}" "$DOCKER_DB_NAME" | gzip > "$SQL_FILE"
|
||||||
|
|
||||||
else
|
else
|
||||||
log "ERRO: DB_MODE inválido ('$DB_MODE'). Use 'remote' ou 'docker'."
|
log "ERRO: DB_MODE inválido ('$DB_MODE'). Use 'remote' ou 'docker'."
|
||||||
|
|||||||
@@ -1,17 +0,0 @@
|
|||||||
#!/usr/bin/env tsx
|
|
||||||
|
|
||||||
import { execSync } from "node:child_process";
|
|
||||||
import { config } from "dotenv";
|
|
||||||
|
|
||||||
// Carregar variáveis de ambiente
|
|
||||||
config();
|
|
||||||
|
|
||||||
const port = process.env.PORT || "3000";
|
|
||||||
|
|
||||||
console.log(`Starting Next.js development server on port ${port}...`);
|
|
||||||
|
|
||||||
// Executar next dev com a porta especificada
|
|
||||||
execSync(`npx next dev --turbopack --port ${port}`, {
|
|
||||||
stdio: "inherit",
|
|
||||||
env: { ...process.env, PORT: port },
|
|
||||||
});
|
|
||||||
245
scripts/install-deps.sh
Executable file
@@ -0,0 +1,245 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# install-deps.sh — Instala pré-requisitos do OpenMonetis
|
||||||
|
# Testado apenas em Ubuntu Server 24.04 LTS
|
||||||
|
# Uso: curl -fsSL https://raw.githubusercontent.com/felipegcoutinho/openmonetis/main/scripts/install-deps.sh -o install-deps.sh
|
||||||
|
# sudo sh install-deps.sh
|
||||||
|
|
||||||
|
set -e
|
||||||
|
|
||||||
|
LOG_FILE="/tmp/openmonetis-install.log"
|
||||||
|
> "$LOG_FILE"
|
||||||
|
|
||||||
|
# Suprimir prompt interativo do corepack ao chamar pnpm/node versioning
|
||||||
|
export COREPACK_ENABLE_DOWNLOAD_PROMPT=0
|
||||||
|
|
||||||
|
# ── Cores ──────────────────────────────────────────────────────────────────────
|
||||||
|
GREEN='\033[0;32m'
|
||||||
|
YELLOW='\033[1;33m'
|
||||||
|
RED='\033[0;31m'
|
||||||
|
CYAN='\033[0;36m'
|
||||||
|
BOLD='\033[1m'
|
||||||
|
RESET='\033[0m'
|
||||||
|
|
||||||
|
ok() { printf "${GREEN}✔${RESET} %s\n" "$1"; }
|
||||||
|
warn() { printf "${YELLOW}!${RESET} %s\n" "$1"; }
|
||||||
|
info() { printf "${CYAN}→${RESET} %s\n" "$1"; }
|
||||||
|
fail() { printf "${RED}✗${RESET} %s\n" "$1"; exit 1; }
|
||||||
|
|
||||||
|
# ── Contador de etapas ─────────────────────────────────────────────────────────
|
||||||
|
_STEP=0
|
||||||
|
_TOTAL=5
|
||||||
|
|
||||||
|
section() {
|
||||||
|
_STEP=$((_STEP + 1))
|
||||||
|
printf "\n${BOLD}[%d/%d] %s${RESET}\n" "$_STEP" "$_TOTAL" "$1"
|
||||||
|
}
|
||||||
|
|
||||||
|
# ── Spinner ────────────────────────────────────────────────────────────────────
|
||||||
|
_spin_pid=""
|
||||||
|
|
||||||
|
spinner_start() {
|
||||||
|
_spin_label="$1"
|
||||||
|
( i=0
|
||||||
|
while true; do
|
||||||
|
case $((i % 4)) in
|
||||||
|
0) d=" " ;; 1) d=". " ;; 2) d=".. " ;; *) d="..." ;;
|
||||||
|
esac
|
||||||
|
printf "\r${CYAN}→${RESET} %s%s" "$_spin_label" "$d"
|
||||||
|
i=$((i + 1))
|
||||||
|
sleep 0.4
|
||||||
|
done
|
||||||
|
) &
|
||||||
|
_spin_pid=$!
|
||||||
|
}
|
||||||
|
|
||||||
|
spinner_stop() {
|
||||||
|
if [ -n "$_spin_pid" ]; then
|
||||||
|
kill "$_spin_pid" 2>/dev/null || true
|
||||||
|
wait "$_spin_pid" 2>/dev/null || true
|
||||||
|
_spin_pid=""
|
||||||
|
printf "\r\033[2K"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
# ── Executores silenciosos com spinner ─────────────────────────────────────────
|
||||||
|
|
||||||
|
# run_quiet "label" cmd [args...] — roda comando com spinner, falha mostra log
|
||||||
|
run_quiet() {
|
||||||
|
_rq_label="$1"; shift
|
||||||
|
spinner_start "$_rq_label"
|
||||||
|
if ! "$@" >> "$LOG_FILE" 2>&1; then
|
||||||
|
spinner_stop
|
||||||
|
printf "${RED}✗ Falha em: %s${RESET}\n" "$_rq_label"
|
||||||
|
printf " Log completo: %s\n\n" "$LOG_FILE"
|
||||||
|
tail -20 "$LOG_FILE"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
spinner_stop
|
||||||
|
}
|
||||||
|
|
||||||
|
# run_as_user "label" "comando_shell" — roda comando como $CURRENT_USER com spinner
|
||||||
|
run_as_user() {
|
||||||
|
_ru_label="$1"; shift
|
||||||
|
spinner_start "$_ru_label"
|
||||||
|
if ! su - "$CURRENT_USER" -c "$*" >> "$LOG_FILE" 2>&1; then
|
||||||
|
spinner_stop
|
||||||
|
printf "${RED}✗ Falha em: %s${RESET}\n" "$_ru_label"
|
||||||
|
printf " Log completo: %s\n\n" "$LOG_FILE"
|
||||||
|
tail -20 "$LOG_FILE"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
spinner_stop
|
||||||
|
}
|
||||||
|
|
||||||
|
# ── Cleanup no Ctrl+C ──────────────────────────────────────────────────────────
|
||||||
|
cleanup() {
|
||||||
|
spinner_stop
|
||||||
|
printf "\n${YELLOW}Instalação interrompida.${RESET} Log em: %s\n" "$LOG_FILE"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
trap cleanup INT TERM
|
||||||
|
|
||||||
|
# ── Tempo total ────────────────────────────────────────────────────────────────
|
||||||
|
_START=$(date +%s)
|
||||||
|
elapsed() {
|
||||||
|
_secs=$(( $(date +%s) - _START ))
|
||||||
|
printf "%dm%ds" $((_secs / 60)) $((_secs % 60))
|
||||||
|
}
|
||||||
|
|
||||||
|
# ── Root check ─────────────────────────────────────────────────────────────────
|
||||||
|
if [ "$(id -u)" -ne 0 ]; then
|
||||||
|
fail "Execute como root ou com sudo: sudo sh install-deps.sh"
|
||||||
|
fi
|
||||||
|
|
||||||
|
CURRENT_USER="${SUDO_USER:-$(whoami)}"
|
||||||
|
|
||||||
|
printf "\n${BOLD}OpenMonetis — Instalação de Dependências${RESET}\n"
|
||||||
|
printf "Usuário: ${CYAN}%s${RESET} | Log: %s\n" "$CURRENT_USER" "$LOG_FILE"
|
||||||
|
|
||||||
|
# ── [1/5] Dependências base ────────────────────────────────────────────────────
|
||||||
|
section "Dependências base"
|
||||||
|
run_quiet "Atualizando lista de pacotes" apt-get update -qq
|
||||||
|
run_quiet "Instalando git, curl, ca-certificates" apt-get install -y -qq ca-certificates curl git
|
||||||
|
ok "git $(git --version | cut -d' ' -f3) · curl · ca-certificates"
|
||||||
|
|
||||||
|
# ── [2/5] Docker ───────────────────────────────────────────────────────────────
|
||||||
|
section "Docker"
|
||||||
|
|
||||||
|
if command -v docker > /dev/null 2>&1; then
|
||||||
|
ok "Docker já instalado: $(docker --version | cut -d',' -f1)"
|
||||||
|
else
|
||||||
|
info "Adicionando repositório oficial do Docker..."
|
||||||
|
install -m 0755 -d /etc/apt/keyrings
|
||||||
|
run_quiet "Baixando chave GPG do Docker" \
|
||||||
|
curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
|
||||||
|
chmod a+r /etc/apt/keyrings/docker.asc
|
||||||
|
|
||||||
|
. /etc/os-release
|
||||||
|
mkdir -p /etc/apt/sources.list.d
|
||||||
|
printf 'deb [arch=%s signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu %s stable\n' \
|
||||||
|
"$(dpkg --print-architecture)" "$VERSION_CODENAME" \
|
||||||
|
> /etc/apt/sources.list.d/docker.list
|
||||||
|
|
||||||
|
run_quiet "Atualizando lista de pacotes" apt-get update -qq
|
||||||
|
run_quiet "Instalando Docker Engine (pode levar alguns minutos)" \
|
||||||
|
apt-get install -y -qq docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
|
||||||
|
|
||||||
|
systemctl enable docker > /dev/null 2>&1 || true
|
||||||
|
systemctl start docker > /dev/null 2>&1 || true
|
||||||
|
ok "Docker $(docker --version | cut -d',' -f1 | cut -d' ' -f3) instalado"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if docker compose version > /dev/null 2>&1; then
|
||||||
|
ok "Docker Compose $(docker compose version | cut -d' ' -f4)"
|
||||||
|
else
|
||||||
|
run_quiet "Instalando Docker Compose plugin" \
|
||||||
|
sh -c 'mkdir -p /usr/local/lib/docker/cli-plugins && curl -fsSL "https://github.com/docker/compose/releases/latest/download/docker-compose-linux-$(uname -m)" -o /usr/local/lib/docker/cli-plugins/docker-compose && chmod +x /usr/local/lib/docker/cli-plugins/docker-compose'
|
||||||
|
ok "Docker Compose $(docker compose version | cut -d' ' -f4) instalado"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ -n "$CURRENT_USER" ] && [ "$CURRENT_USER" != "root" ]; then
|
||||||
|
if ! groups "$CURRENT_USER" | grep -q docker; then
|
||||||
|
usermod -aG docker "$CURRENT_USER"
|
||||||
|
warn "Usuário '$CURRENT_USER' adicionado ao grupo docker — faça logout/login para aplicar"
|
||||||
|
else
|
||||||
|
ok "Usuário '$CURRENT_USER' já está no grupo docker"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# ── [3/5] Homebrew ─────────────────────────────────────────────────────────────
|
||||||
|
section "Homebrew"
|
||||||
|
|
||||||
|
if command -v brew > /dev/null 2>&1; then
|
||||||
|
ok "Homebrew já instalado: $(brew --version | head -1)"
|
||||||
|
else
|
||||||
|
warn "Esta etapa pode levar de 5 a 10 minutos."
|
||||||
|
run_quiet "Instalando dependências de compilação" \
|
||||||
|
apt-get install -y -qq build-essential procps file
|
||||||
|
|
||||||
|
if [ -n "$CURRENT_USER" ] && [ "$CURRENT_USER" != "root" ]; then
|
||||||
|
run_as_user "Instalando Homebrew" \
|
||||||
|
'NONINTERACTIVE=1 bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"'
|
||||||
|
|
||||||
|
BREW_PROFILE="/home/$CURRENT_USER/.bashrc"
|
||||||
|
BREW_EVAL='eval "$(/home/linuxbrew/.linuxbrew/bin/brew shellenv)"'
|
||||||
|
grep -qxF "$BREW_EVAL" "$BREW_PROFILE" 2>/dev/null || echo "$BREW_EVAL" >> "$BREW_PROFILE"
|
||||||
|
export PATH="/home/linuxbrew/.linuxbrew/bin:$PATH"
|
||||||
|
eval "$(/home/linuxbrew/.linuxbrew/bin/brew shellenv)" 2>/dev/null || true
|
||||||
|
else
|
||||||
|
fail "Homebrew não pode ser instalado como root. Use sudo com um usuário normal."
|
||||||
|
fi
|
||||||
|
|
||||||
|
ok "Homebrew instalado"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# ── [4/5] Node.js 22 ───────────────────────────────────────────────────────────
|
||||||
|
section "Node.js 22"
|
||||||
|
|
||||||
|
NODE_MAJOR=0
|
||||||
|
if command -v node > /dev/null 2>&1; then
|
||||||
|
NODE_MAJOR=$(node -e "process.stdout.write(String(parseInt(process.versions.node)))")
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ "$NODE_MAJOR" -ge 22 ] 2>/dev/null; then
|
||||||
|
ok "Node.js já instalado: $(node --version)"
|
||||||
|
else
|
||||||
|
warn "Node.js via Homebrew pode levar alguns minutos."
|
||||||
|
if [ -n "$CURRENT_USER" ] && [ "$CURRENT_USER" != "root" ]; then
|
||||||
|
run_as_user "Instalando Node.js 22" \
|
||||||
|
'eval "$(/home/linuxbrew/.linuxbrew/bin/brew shellenv)" && brew install node@22 && brew link node@22 --force --overwrite'
|
||||||
|
export PATH="/home/linuxbrew/.linuxbrew/bin:$PATH"
|
||||||
|
eval "$(/home/linuxbrew/.linuxbrew/bin/brew shellenv)" 2>/dev/null || true
|
||||||
|
else
|
||||||
|
fail "Node.js via Homebrew não pode ser instalado como root."
|
||||||
|
fi
|
||||||
|
ok "Node.js $(node --version) instalado"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# ── [5/5] pnpm ─────────────────────────────────────────────────────────────────
|
||||||
|
section "pnpm"
|
||||||
|
|
||||||
|
if command -v pnpm > /dev/null 2>&1; then
|
||||||
|
ok "pnpm já instalado: $(pnpm --version)"
|
||||||
|
else
|
||||||
|
if [ -n "$CURRENT_USER" ] && [ "$CURRENT_USER" != "root" ]; then
|
||||||
|
run_as_user "Instalando pnpm via corepack" \
|
||||||
|
'eval "$(/home/linuxbrew/.linuxbrew/bin/brew shellenv)" && corepack enable && COREPACK_ENABLE_DOWNLOAD_PROMPT=0 corepack prepare pnpm@latest --activate'
|
||||||
|
else
|
||||||
|
run_quiet "Instalando pnpm via corepack" \
|
||||||
|
sh -c 'corepack enable && COREPACK_ENABLE_DOWNLOAD_PROMPT=0 corepack prepare pnpm@latest --activate'
|
||||||
|
fi
|
||||||
|
ok "pnpm instalado"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# ── Resumo ─────────────────────────────────────────────────────────────────────
|
||||||
|
# Garantir que node/pnpm do brew estejam no PATH para o resumo
|
||||||
|
export PATH="/home/linuxbrew/.linuxbrew/bin:$PATH"
|
||||||
|
eval "$(/home/linuxbrew/.linuxbrew/bin/brew shellenv)" 2>/dev/null || true
|
||||||
|
|
||||||
|
printf "\n${BOLD}Concluído em $(elapsed)${RESET}\n"
|
||||||
|
|
||||||
|
ok "git: $(git --version | cut -d' ' -f3)"
|
||||||
|
ok "docker: $(docker --version | cut -d',' -f1 | cut -d' ' -f3)"
|
||||||
|
ok "docker compose: $(docker compose version | cut -d' ' -f4)"
|
||||||
|
ok "node: $(node --version)"
|
||||||
|
ok "pnpm: $(pnpm --version)"
|
||||||
1092
scripts/mock-data.ts
@@ -1,45 +0,0 @@
|
|||||||
import * as fs from "node:fs";
|
|
||||||
import * as path from "node:path";
|
|
||||||
import { config } from "dotenv";
|
|
||||||
import { drizzle } from "drizzle-orm/node-postgres";
|
|
||||||
import { Pool } from "pg";
|
|
||||||
|
|
||||||
// Load environment variables from .env
|
|
||||||
config();
|
|
||||||
|
|
||||||
async function initDatabase() {
|
|
||||||
const databaseUrl = process.env.DATABASE_URL;
|
|
||||||
|
|
||||||
if (!databaseUrl) {
|
|
||||||
console.error("DATABASE_URL environment variable is required");
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
const pool = new Pool({ connectionString: databaseUrl });
|
|
||||||
const db = drizzle(pool);
|
|
||||||
|
|
||||||
try {
|
|
||||||
console.log("🔧 Initializing database extensions...");
|
|
||||||
|
|
||||||
// Read and execute init.sql as a single query
|
|
||||||
const initSqlPath = path.join(
|
|
||||||
process.cwd(),
|
|
||||||
"scripts",
|
|
||||||
"postgres",
|
|
||||||
"init.sql",
|
|
||||||
);
|
|
||||||
const initSql = fs.readFileSync(initSqlPath, "utf-8");
|
|
||||||
|
|
||||||
console.log("Executing init.sql...");
|
|
||||||
await db.execute(initSql);
|
|
||||||
|
|
||||||
console.log("✅ Database initialization completed");
|
|
||||||
} catch (error) {
|
|
||||||
console.error("❌ Database initialization failed:", error);
|
|
||||||
process.exit(1);
|
|
||||||
} finally {
|
|
||||||
await pool.end();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
initDatabase();
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
-- Script de inicialização do PostgreSQL para Docker
|
|
||||||
-- Este script é executado automaticamente quando o banco é criado pela primeira vez
|
|
||||||
|
|
||||||
-- Habilitar extensão pgcrypto (necessária para gen_random_bytes usado pelo Drizzle)
|
|
||||||
CREATE EXTENSION IF NOT EXISTS pgcrypto;
|
|
||||||
-- Log de sucesso
|
|
||||||
DO $$
|
|
||||||
BEGIN
|
|
||||||
RAISE NOTICE '✅ Extensão pgcrypto habilitada com sucesso';
|
|
||||||
END $$;
|
|
||||||
@@ -1,49 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
|
|
||||||
# Script para configurar ambiente de forma segura
|
|
||||||
# Cria backup do .env atual antes de sobrescrever
|
|
||||||
|
|
||||||
set -e
|
|
||||||
|
|
||||||
echo "🔧 Configurando ambiente..."
|
|
||||||
|
|
||||||
# Se .env já existe, criar backup
|
|
||||||
if [ -f .env ]; then
|
|
||||||
BACKUP_FILE=".env.backup.$(date +%Y%m%d_%H%M%S)"
|
|
||||||
echo "⚠️ Arquivo .env existente detectado!"
|
|
||||||
echo "📦 Criando backup em: $BACKUP_FILE"
|
|
||||||
cp .env "$BACKUP_FILE"
|
|
||||||
echo "✅ Backup criado com sucesso!"
|
|
||||||
echo ""
|
|
||||||
read -p "Deseja sobrescrever o .env atual com .env.example? (s/N) " -n 1 -r
|
|
||||||
echo
|
|
||||||
if [[ ! $REPLY =~ ^[Ss]$ ]]; then
|
|
||||||
echo "❌ Operação cancelada. Seu .env não foi modificado."
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Copiar .env.example para .env
|
|
||||||
if [ -f .env.example ]; then
|
|
||||||
cp .env.example .env
|
|
||||||
echo "✅ Arquivo .env criado a partir de .env.example"
|
|
||||||
else
|
|
||||||
echo "❌ Erro: .env.example não encontrado!"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Gerar BETTER_AUTH_SECRET automaticamente
|
|
||||||
if command -v openssl &> /dev/null; then
|
|
||||||
SECRET=$(openssl rand -base64 32)
|
|
||||||
sed -i.bak "s|BETTER_AUTH_SECRET=.*|BETTER_AUTH_SECRET=$SECRET|" .env && rm -f .env.bak
|
|
||||||
echo "✅ BETTER_AUTH_SECRET gerado automaticamente"
|
|
||||||
else
|
|
||||||
echo "⚠️ openssl não encontrado — configure BETTER_AUTH_SECRET manualmente:"
|
|
||||||
echo " openssl rand -base64 32"
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo ""
|
|
||||||
echo "⚠️ IMPORTANTE: Edite o arquivo .env e configure:"
|
|
||||||
echo " - DATABASE_URL"
|
|
||||||
echo " - BETTER_AUTH_URL"
|
|
||||||
echo " - Demais variáveis opcionais (OAuth, e-mail, IA)"
|
|
||||||
55
setup.mjs
@@ -21,6 +21,7 @@ const c = {
|
|||||||
red: "\x1b[31m",
|
red: "\x1b[31m",
|
||||||
yellow: "\x1b[33m",
|
yellow: "\x1b[33m",
|
||||||
cyan: "\x1b[36m",
|
cyan: "\x1b[36m",
|
||||||
|
orange: "\x1b[38;5;214m",
|
||||||
};
|
};
|
||||||
|
|
||||||
const sym = {
|
const sym = {
|
||||||
@@ -81,10 +82,38 @@ function abort(msg) {
|
|||||||
|
|
||||||
// ─── Header ──────────────────────────────────────────────────────────────────
|
// ─── Header ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
console.log(`
|
const logoLines = [
|
||||||
${c.bold}${c.cyan} OpenMonetis — Setup${c.reset}
|
".............................+@@@@@@@@@@=.............................",
|
||||||
${c.dim}Gestão financeira self-hosted${c.reset}
|
".............................@@@@@@@@@@@:.............................",
|
||||||
`);
|
"...................+@@@@@@*-:@@@@@@@@@@%...=@@@@@@-...................",
|
||||||
|
"..................@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@%..................",
|
||||||
|
"................=@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@+................",
|
||||||
|
"...................-=+%@@@@@@@@@@@@@@@@@@@@@*:........................",
|
||||||
|
".......................#@@@@@@@@@@@@@@@@@@@@@@@+......................",
|
||||||
|
"....................%@@@@@@@@@@@@@%#@@@@@@@@@@@@*.....................",
|
||||||
|
"....................+@@@@@@@@@@@......*@@@@@@#........................",
|
||||||
|
".........................:#@@=...........+#...........................",
|
||||||
|
];
|
||||||
|
|
||||||
|
const nameLines = [
|
||||||
|
" ___ __ __ _ _ ",
|
||||||
|
" / _ \\ _ __ ___ _ __ | \\/ | ___ _ __ ___| |_(_)___ ",
|
||||||
|
" | | | | '_ \\ / _ \\ '_ \\| |\\/| |/ _ \\| '_ \\ / _ \\ __| / __|",
|
||||||
|
" | |_| | |_) | __/ | | | | | | (_) | | | | __/ |_| \\__ \\",
|
||||||
|
" \\___/| .__/ \\___|_| |_|_| |_|\\___/|_| |_|\\___|\\__|_|___/",
|
||||||
|
" |_| ",
|
||||||
|
];
|
||||||
|
|
||||||
|
const nameStart = Math.floor((logoLines.length - nameLines.length) / 2);
|
||||||
|
|
||||||
|
console.log();
|
||||||
|
for (let i = 0; i < logoLines.length; i++) {
|
||||||
|
const logoCol = c.orange + logoLines[i].replaceAll(".", " ").substring(14, 56).padEnd(42) + c.reset;
|
||||||
|
const nameIdx = i - nameStart;
|
||||||
|
const nameCol = nameIdx >= 0 && nameIdx < nameLines.length ? nameLines[nameIdx] : "";
|
||||||
|
console.log(logoCol + " " + nameCol);
|
||||||
|
}
|
||||||
|
console.log(`\n${" ".repeat(46)}${c.dim}Gestão financeira · self-hosted${c.reset}\n`);
|
||||||
|
|
||||||
// ─── ETAPA 1: Verificações do sistema ────────────────────────────────────────
|
// ─── ETAPA 1: Verificações do sistema ────────────────────────────────────────
|
||||||
|
|
||||||
@@ -200,14 +229,22 @@ if (await askYesNo(" E-mail via Resend (notificações e convites)?")) {
|
|||||||
let anthropicKey = "";
|
let anthropicKey = "";
|
||||||
let openaiKey = "";
|
let openaiKey = "";
|
||||||
let googleAiKey = "";
|
let googleAiKey = "";
|
||||||
|
let minimaxKey = "";
|
||||||
let openrouterKey = "";
|
let openrouterKey = "";
|
||||||
if (await askYesNo(" Insights com IA (Claude, GPT, Gemini, OpenRouter)?")) {
|
let ollamaBaseUrl = "";
|
||||||
|
let ollamaApiKey = "";
|
||||||
|
if (await askYesNo(" Insights com IA (Claude, GPT, Gemini, MiniMax, OpenRouter)?")) {
|
||||||
console.log(` ${c.dim}Deixe em branco o que não for usar${c.reset}`);
|
console.log(` ${c.dim}Deixe em branco o que não for usar${c.reset}`);
|
||||||
anthropicKey = await ask(" ANTHROPIC_API_KEY: ");
|
anthropicKey = await ask(" ANTHROPIC_API_KEY: ");
|
||||||
openaiKey = await ask(" OPENAI_API_KEY: ");
|
openaiKey = await ask(" OPENAI_API_KEY: ");
|
||||||
googleAiKey = await ask(" GOOGLE_GENERATIVE_AI_API_KEY: ");
|
googleAiKey = await ask(" GOOGLE_GENERATIVE_AI_API_KEY: ");
|
||||||
|
minimaxKey = await ask(" MINIMAX_API_KEY: ");
|
||||||
openrouterKey = await ask(" OPENROUTER_API_KEY: ");
|
openrouterKey = await ask(" OPENROUTER_API_KEY: ");
|
||||||
}
|
}
|
||||||
|
if (await askYesNo(" Insights locais com Ollama?")) {
|
||||||
|
ollamaBaseUrl = await askDefault(" OLLAMA_BASE_URL", "http://localhost:11434/v1");
|
||||||
|
ollamaApiKey = await ask(" OLLAMA_API_KEY (opcional): ");
|
||||||
|
}
|
||||||
|
|
||||||
// Domínio público
|
// Domínio público
|
||||||
let publicDomain = "";
|
let publicDomain = "";
|
||||||
@@ -256,6 +293,9 @@ const envContent = [
|
|||||||
"# === Better Auth ===",
|
"# === Better Auth ===",
|
||||||
`BETTER_AUTH_SECRET=${authSecret}`,
|
`BETTER_AUTH_SECRET=${authSecret}`,
|
||||||
`BETTER_AUTH_URL=${betterAuthUrl}`,
|
`BETTER_AUTH_URL=${betterAuthUrl}`,
|
||||||
|
"DISABLE_SIGNUP=false",
|
||||||
|
"AUTH_SESSION_EXPIRES_IN_DAYS=30",
|
||||||
|
"AUTH_SESSION_UPDATE_AGE_HOURS=24",
|
||||||
"",
|
"",
|
||||||
"# === Portas ===",
|
"# === Portas ===",
|
||||||
"APP_PORT=3000",
|
"APP_PORT=3000",
|
||||||
@@ -281,7 +321,10 @@ const envContent = [
|
|||||||
opt("ANTHROPIC_API_KEY", anthropicKey),
|
opt("ANTHROPIC_API_KEY", anthropicKey),
|
||||||
opt("OPENAI_API_KEY", openaiKey),
|
opt("OPENAI_API_KEY", openaiKey),
|
||||||
opt("GOOGLE_GENERATIVE_AI_API_KEY", googleAiKey),
|
opt("GOOGLE_GENERATIVE_AI_API_KEY", googleAiKey),
|
||||||
|
opt("MINIMAX_API_KEY", minimaxKey),
|
||||||
opt("OPENROUTER_API_KEY", openrouterKey),
|
opt("OPENROUTER_API_KEY", openrouterKey),
|
||||||
|
opt("OLLAMA_BASE_URL", ollamaBaseUrl),
|
||||||
|
opt("OLLAMA_API_KEY", ollamaApiKey),
|
||||||
].join("\n");
|
].join("\n");
|
||||||
|
|
||||||
writeFileSync(join(targetDir, ".env"), envContent);
|
writeFileSync(join(targetDir, ".env"), envContent);
|
||||||
@@ -329,7 +372,7 @@ if (useLocalDocker) {
|
|||||||
// Extensões
|
// Extensões
|
||||||
s = spinner("Habilitando extensões do banco...");
|
s = spinner("Habilitando extensões do banco...");
|
||||||
try {
|
try {
|
||||||
run("pnpm db:enableExtensions", { cwd: targetDir });
|
run("pnpm db:extensions", { cwd: targetDir });
|
||||||
s.stop("Extensões habilitadas");
|
s.stop("Extensões habilitadas");
|
||||||
} catch {
|
} catch {
|
||||||
s.fail("Falha ao habilitar extensões");
|
s.fail("Falha ao habilitar extensões");
|
||||||
|
|||||||
23
src/app/(auth)/layout.tsx
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
import { Logo } from "@/shared/components/brand/logo";
|
||||||
|
|
||||||
|
export default function AuthLayout({
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
children: React.ReactNode;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div className="relative flex min-h-svh flex-col items-center justify-center overflow-hidden bg-linear-to-b from-background via-background to-muted/20 px-5 py-8 md:px-8 md:py-10">
|
||||||
|
<div className="pointer-events-none absolute inset-0 overflow-hidden flex items-center justify-center">
|
||||||
|
<div className="absolute -right-32 top-0 h-96 w-96 rounded-full bg-primary/10 blur-3xl animate-blob mix-blend-multiply" />
|
||||||
|
<div className="absolute -left-32 bottom-0 h-96 w-96 rounded-full bg-primary/7 blur-3xl animate-blob animation-delay-2000 mix-blend-multiply" />
|
||||||
|
<div className="absolute -bottom-32 left-1/2 h-80 w-80 rounded-full bg-secondary/30 blur-3xl animate-blob animation-delay-4000 mix-blend-multiply" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="relative mb-6 flex md:hidden z-20">
|
||||||
|
<Logo variant="compact" colorIcon />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="relative w-full max-w-sm md:max-w-5xl">{children}</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,11 +1,6 @@
|
|||||||
import { LoginForm } from "@/features/auth/components/login-form";
|
import { LoginForm } from "@/features/auth/components/login-form";
|
||||||
|
import { isSignupDisabled } from "@/shared/lib/auth/signup";
|
||||||
|
|
||||||
export default function LoginPage() {
|
export default function LoginPage() {
|
||||||
return (
|
return <LoginForm signupDisabled={isSignupDisabled()} />;
|
||||||
<div className="flex min-h-svh flex-col items-center justify-center bg-linear-to-b from-background via-background to-muted/20 px-5 py-8 md:px-8 md:py-10">
|
|
||||||
<div className="w-full max-w-sm md:max-w-5xl">
|
|
||||||
<LoginForm />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
|
import { redirect } from "next/navigation";
|
||||||
import { SignupForm } from "@/features/auth/components/signup-form";
|
import { SignupForm } from "@/features/auth/components/signup-form";
|
||||||
|
import { isSignupDisabled } from "@/shared/lib/auth/signup";
|
||||||
|
|
||||||
export default function Page() {
|
export default function SignupPage() {
|
||||||
return (
|
if (isSignupDisabled()) {
|
||||||
<div className="flex min-h-svh flex-col items-center justify-center bg-linear-to-b from-background via-background to-muted/20 px-5 py-8 md:px-8 md:py-10">
|
redirect("/login");
|
||||||
<div className="w-full max-w-sm md:max-w-5xl">
|
}
|
||||||
<SignupForm />
|
|
||||||
</div>
|
return <SignupForm />;
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,15 @@
|
|||||||
import { RiPencilLine } from "@remixicon/react";
|
import { RiPencilLine } from "@remixicon/react";
|
||||||
import { notFound } from "next/navigation";
|
import { notFound } from "next/navigation";
|
||||||
|
import { connection } from "next/server";
|
||||||
import { AccountDialog } from "@/features/accounts/components/account-dialog";
|
import { AccountDialog } from "@/features/accounts/components/account-dialog";
|
||||||
import { AccountStatementCard } from "@/features/accounts/components/account-statement-card";
|
import { AccountStatementCard } from "@/features/accounts/components/account-statement-card";
|
||||||
|
import { AddYieldDialog } from "@/features/accounts/components/add-yield-dialog";
|
||||||
|
import { AdjustBalanceDialog } from "@/features/accounts/components/adjust-balance-dialog";
|
||||||
import type { Account } from "@/features/accounts/components/types";
|
import type { Account } from "@/features/accounts/components/types";
|
||||||
import {
|
import {
|
||||||
fetchAccountData,
|
fetchAccountData,
|
||||||
fetchAccountLancamentosPage,
|
|
||||||
fetchAccountSummary,
|
fetchAccountSummary,
|
||||||
|
fetchAccountTransactionsPage,
|
||||||
} from "@/features/accounts/statement-queries";
|
} from "@/features/accounts/statement-queries";
|
||||||
import { fetchUserPreferences } from "@/features/settings/queries";
|
import { fetchUserPreferences } from "@/features/settings/queries";
|
||||||
import { TransactionsPage as LancamentosSection } from "@/features/transactions/components/page/transactions-page";
|
import { TransactionsPage as LancamentosSection } from "@/features/transactions/components/page/transactions-page";
|
||||||
@@ -20,7 +23,7 @@ import {
|
|||||||
mapTransactionsData,
|
mapTransactionsData,
|
||||||
type ResolvedSearchParams,
|
type ResolvedSearchParams,
|
||||||
resolveTransactionPagination,
|
resolveTransactionPagination,
|
||||||
} from "@/features/transactions/page-helpers";
|
} from "@/features/transactions/lib/page-helpers";
|
||||||
import {
|
import {
|
||||||
fetchRecentEstablishments,
|
fetchRecentEstablishments,
|
||||||
fetchTransactionFilterSources,
|
fetchTransactionFilterSources,
|
||||||
@@ -29,6 +32,7 @@ import MonthNavigation from "@/shared/components/month-picker/month-navigation";
|
|||||||
import { Button } from "@/shared/components/ui/button";
|
import { Button } from "@/shared/components/ui/button";
|
||||||
import { getUserId } from "@/shared/lib/auth/server";
|
import { getUserId } from "@/shared/lib/auth/server";
|
||||||
import { loadLogoOptions } from "@/shared/lib/logo/options";
|
import { loadLogoOptions } from "@/shared/lib/logo/options";
|
||||||
|
import { getBusinessDateString } from "@/shared/utils/date";
|
||||||
import { parsePeriodParam } from "@/shared/utils/period";
|
import { parsePeriodParam } from "@/shared/utils/period";
|
||||||
|
|
||||||
type PageSearchParams = Promise<ResolvedSearchParams>;
|
type PageSearchParams = Promise<ResolvedSearchParams>;
|
||||||
@@ -41,7 +45,28 @@ type PageProps = {
|
|||||||
const capitalize = (value: string) =>
|
const capitalize = (value: string) =>
|
||||||
value.length > 0 ? value[0]?.toUpperCase().concat(value.slice(1)) : value;
|
value.length > 0 ? value[0]?.toUpperCase().concat(value.slice(1)) : value;
|
||||||
|
|
||||||
|
const resolveDefaultPaymentMethod = (
|
||||||
|
accountType: string | null | undefined,
|
||||||
|
) => {
|
||||||
|
if (accountType === "Dinheiro") return "Dinheiro";
|
||||||
|
if (accountType === "Pré-Pago | VR/VA") return "Pré-Pago | VR/VA";
|
||||||
|
|
||||||
|
return "Pix";
|
||||||
|
};
|
||||||
|
|
||||||
|
const resolveDefaultYieldDate = (period: string) => {
|
||||||
|
const today = getBusinessDateString();
|
||||||
|
if (today.startsWith(period)) return today;
|
||||||
|
|
||||||
|
const [year, month] = period.split("-").map((part) => Number(part));
|
||||||
|
if (!year || !month) return today;
|
||||||
|
|
||||||
|
const lastDay = new Date(year, month, 0).getDate();
|
||||||
|
return `${period}-${String(lastDay).padStart(2, "0")}`;
|
||||||
|
};
|
||||||
|
|
||||||
export default async function Page({ params, searchParams }: PageProps) {
|
export default async function Page({ params, searchParams }: PageProps) {
|
||||||
|
await connection();
|
||||||
const { accountId } = await params;
|
const { accountId } = await params;
|
||||||
const userId = await getUserId();
|
const userId = await getUserId();
|
||||||
const resolvedSearchParams = searchParams ? await searchParams : undefined;
|
const resolvedSearchParams = searchParams ? await searchParams : undefined;
|
||||||
@@ -84,9 +109,11 @@ 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 fetchAccountLancamentosPage(
|
const transactionsPage = await fetchAccountTransactionsPage(
|
||||||
filters,
|
filters,
|
||||||
pagination,
|
pagination,
|
||||||
);
|
);
|
||||||
@@ -97,6 +124,7 @@ export default async function Page({ params, searchParams }: PageProps) {
|
|||||||
accountSummary;
|
accountSummary;
|
||||||
|
|
||||||
const periodLabel = `${capitalize(monthName)} de ${year}`;
|
const periodLabel = `${capitalize(monthName)} de ${year}`;
|
||||||
|
const defaultYieldDate = resolveDefaultYieldDate(selectedPeriod);
|
||||||
|
|
||||||
const accountDialogData: Account = {
|
const accountDialogData: Account = {
|
||||||
id: account.id,
|
id: account.id,
|
||||||
@@ -139,6 +167,19 @@ export default async function Page({ params, searchParams }: PageProps) {
|
|||||||
totalIncomes={totalIncomes}
|
totalIncomes={totalIncomes}
|
||||||
totalExpenses={totalExpenses}
|
totalExpenses={totalExpenses}
|
||||||
logo={account.logo}
|
logo={account.logo}
|
||||||
|
balanceAdjustment={
|
||||||
|
<>
|
||||||
|
<AddYieldDialog
|
||||||
|
accountId={account.id}
|
||||||
|
defaultDate={defaultYieldDate}
|
||||||
|
/>
|
||||||
|
<AdjustBalanceDialog
|
||||||
|
accountId={account.id}
|
||||||
|
period={selectedPeriod}
|
||||||
|
currentBalance={currentBalance}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
}
|
||||||
actions={
|
actions={
|
||||||
<AccountDialog
|
<AccountDialog
|
||||||
mode="update"
|
mode="update"
|
||||||
@@ -187,9 +228,17 @@ export default async function Page({ params, searchParams }: PageProps) {
|
|||||||
accountId: account.id,
|
accountId: account.id,
|
||||||
settledOnly: true,
|
settledOnly: true,
|
||||||
}}
|
}}
|
||||||
allowCreate={false}
|
allowCreate
|
||||||
|
defaultAccountId={account.id}
|
||||||
|
defaultPaymentMethod={resolveDefaultPaymentMethod(
|
||||||
|
account.accountType,
|
||||||
|
)}
|
||||||
noteAsColumn={userPreferences?.statementNoteAsColumn ?? false}
|
noteAsColumn={userPreferences?.statementNoteAsColumn ?? false}
|
||||||
columnOrder={userPreferences?.transactionsColumnOrder ?? null}
|
columnOrder={userPreferences?.transactionsColumnOrder ?? null}
|
||||||
|
groupTransactionsByDate={
|
||||||
|
userPreferences?.groupTransactionsByDate ?? true
|
||||||
|
}
|
||||||
|
attachmentMaxSizeMb={userPreferences?.attachmentMaxSizeMb ?? 50}
|
||||||
/>
|
/>
|
||||||
</section>
|
</section>
|
||||||
</main>
|
</main>
|
||||||
|
|||||||
@@ -11,13 +11,12 @@ export default function RootLayout({
|
|||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<section className="space-y-6 pt-4">
|
<section className="space-y-6">
|
||||||
<PageDescription
|
<PageDescription
|
||||||
icon={<RiBankLine />}
|
icon={<RiBankLine />}
|
||||||
title="Contas"
|
title="Contas"
|
||||||
subtitle="Acompanhe todas as contas do mês selecionado incluindo receitas,
|
subtitle="Acompanhe todas as contas do mês selecionado incluindo receitas,
|
||||||
despesas e transações previstas. Use o seletor abaixo para navegar pelos
|
despesas e transações previstas."
|
||||||
meses e visualizar as movimentações correspondentes."
|
|
||||||
/>
|
/>
|
||||||
{children}
|
{children}
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
|
import { connection } from "next/server";
|
||||||
import { AccountsPage } from "@/features/accounts/components/accounts-page";
|
import { AccountsPage } from "@/features/accounts/components/accounts-page";
|
||||||
import { fetchAllAccountsForUser } from "@/features/accounts/queries";
|
import { fetchAllAccountsForUser } from "@/features/accounts/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();
|
||||||
const userId = await getUserId();
|
const userId = await getUserId();
|
||||||
const { activeAccounts, archivedAccounts, logoOptions } =
|
const { activeAccounts, archivedAccounts, logoOptions } =
|
||||||
await fetchAllAccountsForUser(userId);
|
await fetchAllAccountsForUser(userId);
|
||||||
|
|||||||
25
src/app/(dashboard)/attachments/layout.tsx
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
import { RiAttachmentLine } from "@remixicon/react";
|
||||||
|
import MonthNavigation from "@/shared/components/month-picker/month-navigation";
|
||||||
|
import PageDescription from "@/shared/components/page-description";
|
||||||
|
|
||||||
|
export const metadata = {
|
||||||
|
title: "Anexos",
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function RootLayout({
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
children: React.ReactNode;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<section className="space-y-6">
|
||||||
|
<PageDescription
|
||||||
|
icon={<RiAttachmentLine />}
|
||||||
|
title="Anexos"
|
||||||
|
subtitle="Gerencie os anexos das suas transações"
|
||||||
|
/>
|
||||||
|
<MonthNavigation />
|
||||||
|
{children}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
38
src/app/(dashboard)/attachments/loading.tsx
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
import { Skeleton } from "@/shared/components/ui/skeleton";
|
||||||
|
|
||||||
|
export default function AnexosLoading() {
|
||||||
|
return (
|
||||||
|
<main className="flex flex-col gap-6">
|
||||||
|
<div className="w-full space-y-6">
|
||||||
|
{/* Header */}
|
||||||
|
<Skeleton className="h-10 w-40 rounded-md bg-foreground/10" />
|
||||||
|
|
||||||
|
{/* Month navigation */}
|
||||||
|
<Skeleton className="h-10 w-64 rounded-md bg-foreground/10" />
|
||||||
|
|
||||||
|
{/* Count */}
|
||||||
|
<Skeleton className="h-4 w-20 rounded-md bg-foreground/10" />
|
||||||
|
|
||||||
|
{/* Grid */}
|
||||||
|
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5">
|
||||||
|
{Array.from({ length: 10 }).map((_, i) => (
|
||||||
|
<div
|
||||||
|
key={i}
|
||||||
|
className="flex flex-col overflow-hidden rounded-lg border"
|
||||||
|
>
|
||||||
|
<Skeleton className="aspect-square w-full bg-foreground/10" />
|
||||||
|
<div className="space-y-1.5 p-2.5">
|
||||||
|
<Skeleton className="h-3 w-3/4 rounded bg-foreground/10" />
|
||||||
|
<Skeleton className="h-3 w-full rounded bg-foreground/10" />
|
||||||
|
<div className="flex justify-between">
|
||||||
|
<Skeleton className="h-3 w-16 rounded bg-foreground/10" />
|
||||||
|
<Skeleton className="h-3 w-12 rounded bg-foreground/10" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
39
src/app/(dashboard)/attachments/page.tsx
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
import { connection } from "next/server";
|
||||||
|
import { AttachmentsPage } from "@/features/attachments/components/attachments-page";
|
||||||
|
import { fetchAttachmentsPageData } from "@/features/attachments/queries";
|
||||||
|
import { getUserId } from "@/shared/lib/auth/server";
|
||||||
|
import { parsePeriodParam } from "@/shared/utils/period";
|
||||||
|
|
||||||
|
type PageSearchParams = Promise<Record<string, string | string[] | undefined>>;
|
||||||
|
|
||||||
|
type PageProps = {
|
||||||
|
searchParams?: PageSearchParams;
|
||||||
|
};
|
||||||
|
|
||||||
|
const getSingleParam = (
|
||||||
|
params: Record<string, string | string[] | undefined> | undefined,
|
||||||
|
key: string,
|
||||||
|
) => {
|
||||||
|
const value = params?.[key];
|
||||||
|
if (!value) return null;
|
||||||
|
return Array.isArray(value) ? (value[0] ?? null) : value;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default async function Page({ searchParams }: PageProps) {
|
||||||
|
await connection();
|
||||||
|
const userId = await getUserId();
|
||||||
|
const resolvedSearchParams = searchParams ? await searchParams : undefined;
|
||||||
|
const periodoParam = getSingleParam(resolvedSearchParams, "periodo");
|
||||||
|
const { period } = parsePeriodParam(periodoParam);
|
||||||
|
|
||||||
|
const data = await fetchAttachmentsPageData(userId, period);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<main className="flex flex-col gap-6">
|
||||||
|
<AttachmentsPage
|
||||||
|
attachments={data?.attachments ?? []}
|
||||||
|
adminPayerId={data?.adminPayerId ?? ""}
|
||||||
|
/>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -11,7 +11,7 @@ export default function RootLayout({
|
|||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<section className="space-y-6 pt-4">
|
<section className="space-y-6">
|
||||||
<PageDescription
|
<PageDescription
|
||||||
icon={<RiBarChart2Line />}
|
icon={<RiBarChart2Line />}
|
||||||
title="Orçamentos"
|
title="Orçamentos"
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { connection } from "next/server";
|
||||||
import { BudgetsPage } from "@/features/budgets/components/budgets-page";
|
import { BudgetsPage } from "@/features/budgets/components/budgets-page";
|
||||||
import { fetchBudgetsForUser } from "@/features/budgets/queries";
|
import { fetchBudgetsForUser } from "@/features/budgets/queries";
|
||||||
import MonthNavigation from "@/shared/components/month-picker/month-navigation";
|
import MonthNavigation from "@/shared/components/month-picker/month-navigation";
|
||||||
@@ -19,22 +20,12 @@ const getSingleParam = (
|
|||||||
return Array.isArray(value) ? (value[0] ?? null) : value;
|
return Array.isArray(value) ? (value[0] ?? null) : value;
|
||||||
};
|
};
|
||||||
|
|
||||||
const capitalize = (value: string) =>
|
|
||||||
value.length === 0 ? value : value[0]?.toUpperCase() + value.slice(1);
|
|
||||||
|
|
||||||
export default async function Page({ searchParams }: PageProps) {
|
export default async function Page({ searchParams }: PageProps) {
|
||||||
|
await connection();
|
||||||
const userId = await getUserId();
|
const userId = await getUserId();
|
||||||
const resolvedSearchParams = searchParams ? await searchParams : undefined;
|
const resolvedSearchParams = searchParams ? await searchParams : undefined;
|
||||||
const periodoParam = getSingleParam(resolvedSearchParams, "periodo");
|
const periodoParam = getSingleParam(resolvedSearchParams, "periodo");
|
||||||
|
const { period: selectedPeriod } = parsePeriodParam(periodoParam);
|
||||||
const {
|
|
||||||
period: selectedPeriod,
|
|
||||||
monthName: rawMonthName,
|
|
||||||
year,
|
|
||||||
} = parsePeriodParam(periodoParam);
|
|
||||||
|
|
||||||
const periodLabel = `${capitalize(rawMonthName)} ${year}`;
|
|
||||||
|
|
||||||
const { budgets, categoriesOptions } = await fetchBudgetsForUser(
|
const { budgets, categoriesOptions } = await fetchBudgetsForUser(
|
||||||
userId,
|
userId,
|
||||||
selectedPeriod,
|
selectedPeriod,
|
||||||
@@ -47,7 +38,6 @@ export default async function Page({ searchParams }: PageProps) {
|
|||||||
budgets={budgets}
|
budgets={budgets}
|
||||||
categories={categoriesOptions}
|
categories={categoriesOptions}
|
||||||
selectedPeriod={selectedPeriod}
|
selectedPeriod={selectedPeriod}
|
||||||
periodLabel={periodLabel}
|
|
||||||
/>
|
/>
|
||||||
</main>
|
</main>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ export default function RootLayout({
|
|||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<section className="space-y-6 pt-4">
|
<section className="space-y-6">
|
||||||
<PageDescription
|
<PageDescription
|
||||||
icon={<RiCalendarEventLine />}
|
icon={<RiCalendarEventLine />}
|
||||||
title="Calendário"
|
title="Calendário"
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
|
import { connection } from "next/server";
|
||||||
import { MonthlyCalendar } from "@/features/calendar/components/monthly-calendar";
|
import { MonthlyCalendar } from "@/features/calendar/components/monthly-calendar";
|
||||||
import { fetchCalendarData } from "@/features/calendar/queries";
|
import { fetchCalendarData } from "@/features/calendar/queries";
|
||||||
import {
|
import {
|
||||||
getSingleParam,
|
getSingleParam,
|
||||||
type ResolvedSearchParams,
|
type ResolvedSearchParams,
|
||||||
} from "@/features/transactions/page-helpers";
|
} from "@/features/transactions/lib/page-helpers";
|
||||||
import MonthNavigation from "@/shared/components/month-picker/month-navigation";
|
import MonthNavigation from "@/shared/components/month-picker/month-navigation";
|
||||||
import { getUserId } from "@/shared/lib/auth/server";
|
import { getUserId } from "@/shared/lib/auth/server";
|
||||||
import type { CalendarPeriod } from "@/shared/lib/types/calendar";
|
import type { CalendarPeriod } from "@/shared/lib/types/calendar";
|
||||||
@@ -16,6 +17,7 @@ type PageProps = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export default async function Page({ searchParams }: PageProps) {
|
export default async function Page({ searchParams }: PageProps) {
|
||||||
|
await connection();
|
||||||
const userId = await getUserId();
|
const userId = await getUserId();
|
||||||
const resolvedParams = searchParams ? await searchParams : undefined;
|
const resolvedParams = searchParams ? await searchParams : undefined;
|
||||||
|
|
||||||
@@ -34,7 +36,7 @@ export default async function Page({ searchParams }: PageProps) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="flex flex-col gap-3">
|
<main className="flex flex-col gap-4">
|
||||||
<MonthNavigation />
|
<MonthNavigation />
|
||||||
<MonthlyCalendar
|
<MonthlyCalendar
|
||||||
period={calendarPeriod}
|
period={calendarPeriod}
|
||||||
|
|||||||