mirror of
https://github.com/felipegcoutinho/openmonetis.git
synced 2026-05-09 19:01:47 +00:00
Compare commits
5 Commits
v2.3.1
...
85f6dcfc22
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
85f6dcfc22 | ||
|
|
df996df93d | ||
|
|
10afef9fec | ||
|
|
fd4d90a53e | ||
|
|
a24406271c |
1
.github/workflows/docker-publish.yml
vendored
1
.github/workflows/docker-publish.yml
vendored
@@ -13,6 +13,7 @@ on:
|
|||||||
|
|
||||||
env:
|
env:
|
||||||
DOCKER_IMAGE_NAME: openmonetis
|
DOCKER_IMAGE_NAME: openmonetis
|
||||||
|
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
quality:
|
quality:
|
||||||
|
|||||||
3
.github/workflows/release.yml
vendored
3
.github/workflows/release.yml
vendored
@@ -5,6 +5,9 @@ on:
|
|||||||
branches:
|
branches:
|
||||||
- main
|
- main
|
||||||
|
|
||||||
|
env:
|
||||||
|
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
release:
|
release:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|||||||
15
CHANGELOG.md
15
CHANGELOG.md
@@ -7,6 +7,21 @@ e este projeto adere ao [Versionamento Semântico](https://semver.org/lang/pt-BR
|
|||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
|
## [2.3.2] - 2026-04-04
|
||||||
|
|
||||||
|
### Segurança
|
||||||
|
|
||||||
|
- Tokens: removido aceite de tokens sem expiração (`expiresAt NULL`); tokens criados via settings agora expiram em 1 ano
|
||||||
|
- Tokens: corrigido refresh que sobrescrevia hash e invalidava access token anterior; verify agora valida JWT por assinatura
|
||||||
|
- xlsx: desabilitado parsing de fórmulas (`cellFormula: false`) para mitigar CVE-2024-44294
|
||||||
|
- CSP: expandida Content-Security-Policy com `default-src`, `script-src`, `style-src`, `img-src`, `font-src` e `connect-src`
|
||||||
|
- Headers: adicionados `Referrer-Policy` e `X-Permitted-Cross-Domain-Policies`
|
||||||
|
- API: rotas autenticadas agora retornam `401 JSON` em vez de redirect `302` para clientes não autenticados
|
||||||
|
- Health: removido campo `version` da resposta do `/api/health`
|
||||||
|
- robots.txt: simplificado para não expor mapa de rotas internas
|
||||||
|
- Sitemap: corrigida URL com protocolo duplicado (`https://https://`)
|
||||||
|
- Criado `security.txt` (RFC 9116)
|
||||||
|
|
||||||
## [2.3.1] - 2026-04-03
|
## [2.3.1] - 2026-04-03
|
||||||
|
|
||||||
### Corrigido
|
### Corrigido
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import type { NextConfig } from "next";
|
|||||||
// Carregar variáveis de ambiente explicitamente
|
// Carregar variáveis de ambiente explicitamente
|
||||||
dotenv.config();
|
dotenv.config();
|
||||||
|
|
||||||
|
const isDev = process.env.NODE_ENV === "development";
|
||||||
|
|
||||||
const nextConfig: NextConfig = {
|
const nextConfig: NextConfig = {
|
||||||
output: "standalone",
|
output: "standalone",
|
||||||
cacheComponents: true,
|
cacheComponents: true,
|
||||||
@@ -44,7 +46,23 @@ const nextConfig: NextConfig = {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: "Content-Security-Policy",
|
key: "Content-Security-Policy",
|
||||||
value: "frame-ancestors 'none';",
|
value: [
|
||||||
|
"default-src 'self'",
|
||||||
|
`script-src 'self' 'unsafe-inline'${isDev ? " 'unsafe-eval'" : ""} https://umami.felipecoutinho.com`,
|
||||||
|
"style-src 'self' 'unsafe-inline'",
|
||||||
|
"img-src 'self' https://lh3.googleusercontent.com data: blob:",
|
||||||
|
"font-src 'self'",
|
||||||
|
"connect-src 'self' https://umami.felipecoutinho.com",
|
||||||
|
"frame-ancestors 'none'",
|
||||||
|
].join("; "),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: "Referrer-Policy",
|
||||||
|
value: "strict-origin-when-cross-origin",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: "X-Permitted-Cross-Domain-Policies",
|
||||||
|
value: "none",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: "Permissions-Policy",
|
key: "Permissions-Policy",
|
||||||
|
|||||||
212
package.json
212
package.json
@@ -1,108 +1,108 @@
|
|||||||
{
|
{
|
||||||
"name": "openmonetis",
|
"name": "openmonetis",
|
||||||
"version": "2.3.1",
|
"version": "2.3.2",
|
||||||
"private": true,
|
"private": true,
|
||||||
"packageManager": "pnpm@10.33.0",
|
"packageManager": "pnpm@10.33.0",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "next dev --turbopack",
|
"dev": "next dev --turbopack",
|
||||||
"db:seed": "tsx scripts/mock-data.ts",
|
"db:seed": "tsx scripts/mock-data.ts",
|
||||||
"build": "next build",
|
"build": "next build",
|
||||||
"start": "next start",
|
"start": "next start",
|
||||||
"lint": "biome check .",
|
"lint": "biome check .",
|
||||||
"lint:deadcode": "knip --reporter compact",
|
"lint:deadcode": "knip --reporter compact",
|
||||||
"lint:fix": "biome check --write .",
|
"lint:fix": "biome check --write .",
|
||||||
"env:setup": "bash scripts/setup-env.sh",
|
"env:setup": "bash scripts/setup-env.sh",
|
||||||
"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:extensions": "tsx scripts/postgres/enable-extensions.ts",
|
"db:extensions": "tsx scripts/postgres/enable-extensions.ts",
|
||||||
"db:studio": "drizzle-kit studio",
|
"db:studio": "drizzle-kit studio",
|
||||||
"docker:up": "docker compose up --build",
|
"docker:up": "docker compose up --build",
|
||||||
"postinstall": "cp node_modules/pdfjs-dist/build/pdf.worker.min.mjs public/pdf.worker.min.mjs",
|
"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:db": "docker compose up -d db",
|
||||||
"docker:up:d": "docker compose up --build -d",
|
"docker:up:d": "docker compose up --build -d",
|
||||||
"docker:down": "docker compose down",
|
"docker:down": "docker compose down",
|
||||||
"docker:down:volumes": "docker compose down -v",
|
"docker:down:volumes": "docker compose down -v",
|
||||||
"docker:logs": "docker compose logs -f",
|
"docker:logs": "docker compose logs -f",
|
||||||
"docker:logs:app": "docker compose logs -f app",
|
"docker:logs:app": "docker compose logs -f app",
|
||||||
"docker:logs:db": "docker compose logs -f db",
|
"docker:logs:db": "docker compose logs -f db",
|
||||||
"docker:restart": "docker compose restart",
|
"docker:restart": "docker compose restart",
|
||||||
"docker:rebuild": "docker compose up --build --force-recreate",
|
"docker:rebuild": "docker compose up --build --force-recreate",
|
||||||
"backup": "bash scripts/backup.sh"
|
"backup": "bash scripts/backup.sh"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ai-sdk/anthropic": "^3.0.65",
|
"@ai-sdk/anthropic": "^3.0.65",
|
||||||
"@ai-sdk/google": "^3.0.55",
|
"@ai-sdk/google": "^3.0.55",
|
||||||
"@ai-sdk/openai": "^3.0.49",
|
"@ai-sdk/openai": "^3.0.49",
|
||||||
"@aws-sdk/client-s3": "^3.1022.0",
|
"@aws-sdk/client-s3": "^3.1022.0",
|
||||||
"@aws-sdk/s3-request-presigner": "^3.1022.0",
|
"@aws-sdk/s3-request-presigner": "^3.1022.0",
|
||||||
"@better-auth/passkey": "^1.5.6",
|
"@better-auth/passkey": "^1.5.6",
|
||||||
"@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.3.3",
|
||||||
"@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.15",
|
||||||
"@radix-ui/react-label": "2.1.8",
|
"@radix-ui/react-label": "2.1.8",
|
||||||
"@radix-ui/react-popover": "^1.1.15",
|
"@radix-ui/react-popover": "^1.1.15",
|
||||||
"@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.3.8",
|
||||||
"@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-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",
|
||||||
"@radix-ui/react-toggle": "1.1.10",
|
"@radix-ui/react-toggle": "1.1.10",
|
||||||
"@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.96.2",
|
"@tanstack/react-query": "^5.96.2",
|
||||||
"@tanstack/react-table": "8.21.3",
|
"@tanstack/react-table": "8.21.3",
|
||||||
"@tanstack/react-virtual": "^3.13.23",
|
"@tanstack/react-virtual": "^3.13.23",
|
||||||
"ai": "^6.0.143",
|
"ai": "^6.0.143",
|
||||||
"better-auth": "1.5.6",
|
"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.1.0",
|
||||||
"drizzle-orm": "0.45.2",
|
"drizzle-orm": "0.45.2",
|
||||||
"jspdf": "^4.2.1",
|
"exceljs": "^4.4.0",
|
||||||
"jspdf-autotable": "^5.0.7",
|
"jspdf": "^4.2.1",
|
||||||
"next": "16.2.2",
|
"jspdf-autotable": "^5.0.7",
|
||||||
"next-themes": "0.4.6",
|
"next": "16.2.2",
|
||||||
"pdfjs-dist": "^5.6.205",
|
"next-themes": "0.4.6",
|
||||||
"pg": "8.20.0",
|
"pdfjs-dist": "^5.6.205",
|
||||||
"radix-ui": "^1.4.3",
|
"pg": "8.20.0",
|
||||||
"react": "19.2.4",
|
"radix-ui": "^1.4.3",
|
||||||
"react-day-picker": "^9.14.0",
|
"react": "19.2.4",
|
||||||
"react-dom": "19.2.4",
|
"react-day-picker": "^9.14.0",
|
||||||
"recharts": "3.8.1",
|
"react-dom": "19.2.4",
|
||||||
"resend": "^6.10.0",
|
"recharts": "3.8.1",
|
||||||
"sonner": "2.0.7",
|
"resend": "^6.10.0",
|
||||||
"tailwind-merge": "3.5.0",
|
"sonner": "2.0.7",
|
||||||
"vaul": "1.1.2",
|
"tailwind-merge": "3.5.0",
|
||||||
"xlsx": "^0.18.5",
|
"vaul": "1.1.2",
|
||||||
"zod": "4.3.6"
|
"zod": "4.3.6"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@biomejs/biome": "2.4.10",
|
"@biomejs/biome": "2.4.10",
|
||||||
"@tailwindcss/postcss": "4.2.2",
|
"@tailwindcss/postcss": "4.2.2",
|
||||||
"@types/canvas-confetti": "^1.9.0",
|
"@types/canvas-confetti": "^1.9.0",
|
||||||
"@types/node": "25.5.0",
|
"@types/node": "25.5.0",
|
||||||
"@types/pg": "^8.20.0",
|
"@types/pg": "^8.20.0",
|
||||||
"@types/react": "19.2.14",
|
"@types/react": "19.2.14",
|
||||||
"@types/react-dom": "19.2.3",
|
"@types/react-dom": "19.2.3",
|
||||||
"dotenv": "^17.4.0",
|
"dotenv": "^17.4.0",
|
||||||
"drizzle-kit": "0.31.10",
|
"drizzle-kit": "0.31.10",
|
||||||
"knip": "^6.3.0",
|
"knip": "^6.3.0",
|
||||||
"tailwindcss": "4.2.2",
|
"tailwindcss": "4.2.2",
|
||||||
"tsx": "4.21.0",
|
"tsx": "4.21.0",
|
||||||
"typescript": "6.0.2"
|
"typescript": "6.0.2"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
646
pnpm-lock.yaml
generated
646
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
4
public/.well-known/security.txt
Normal file
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
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import { and, eq } from "drizzle-orm";
|
import { and, eq } from "drizzle-orm";
|
||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { attachments } from "@/db/schema";
|
import { attachments } from "@/db/schema";
|
||||||
import { getUserId } from "@/shared/lib/auth/server";
|
import { getOptionalUserSession } from "@/shared/lib/auth/server";
|
||||||
import { db } from "@/shared/lib/db";
|
import { db } from "@/shared/lib/db";
|
||||||
import { createPresignedGetUrl } from "@/shared/lib/storage/presign";
|
import { createPresignedGetUrl } from "@/shared/lib/storage/presign";
|
||||||
|
|
||||||
@@ -13,7 +13,19 @@ export async function GET(
|
|||||||
_request: Request,
|
_request: Request,
|
||||||
{ params }: { params: Promise<{ attachmentId: string }> },
|
{ params }: { params: Promise<{ attachmentId: string }> },
|
||||||
) {
|
) {
|
||||||
const [userId, { attachmentId }] = await Promise.all([getUserId(), params]);
|
const [session, { attachmentId }] = await Promise.all([
|
||||||
|
getOptionalUserSession(),
|
||||||
|
params,
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (!session?.user) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Não autenticado" },
|
||||||
|
{ status: 401, headers: PRIVATE_RESPONSE_HEADERS },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const userId = session.user.id;
|
||||||
|
|
||||||
const [row] = await db
|
const [row] = await db
|
||||||
.select({ fileKey: attachments.fileKey })
|
.select({ fileKey: attachments.fileKey })
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ import { NextResponse } from "next/server";
|
|||||||
import { apiTokens } from "@/db/schema";
|
import { apiTokens } from "@/db/schema";
|
||||||
import {
|
import {
|
||||||
extractBearerToken,
|
extractBearerToken,
|
||||||
hashToken,
|
|
||||||
refreshAccessToken,
|
refreshAccessToken,
|
||||||
verifyJwt,
|
verifyJwt,
|
||||||
} from "@/shared/lib/auth/api-token";
|
} from "@/shared/lib/auth/api-token";
|
||||||
@@ -59,11 +58,11 @@ export async function POST(request: Request) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Atualizar hash do token e último uso
|
// Atualizar último uso e expiração (sem sobrescrever tokenHash,
|
||||||
|
// pois o JWT é auto-verificável por assinatura)
|
||||||
await db
|
await db
|
||||||
.update(apiTokens)
|
.update(apiTokens)
|
||||||
.set({
|
.set({
|
||||||
tokenHash: hashToken(result.accessToken),
|
|
||||||
lastUsedAt: new Date(),
|
lastUsedAt: new Date(),
|
||||||
lastUsedIp:
|
lastUsedIp:
|
||||||
request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ||
|
request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ||
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { and, eq, gt, isNull } from "drizzle-orm";
|
import { and, eq, gt, isNull } from "drizzle-orm";
|
||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { apiTokens } from "@/db/schema";
|
import { apiTokens } from "@/db/schema";
|
||||||
import { extractBearerToken, hashToken } from "@/shared/lib/auth/api-token";
|
import { extractBearerToken, verifyJwt } from "@/shared/lib/auth/api-token";
|
||||||
import { db } from "@/shared/lib/db";
|
import { db } from "@/shared/lib/db";
|
||||||
|
|
||||||
export async function POST(request: Request) {
|
export async function POST(request: Request) {
|
||||||
@@ -17,21 +17,21 @@ export async function POST(request: Request) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validar token os_xxx via hash lookup
|
// Verificar JWT (assinatura + expiração)
|
||||||
if (!token.startsWith("os_")) {
|
const payload = verifyJwt(token);
|
||||||
|
|
||||||
|
if (!payload || payload.type !== "api_access") {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ valid: false, error: "Formato de token inválido" },
|
{ valid: false, error: "Token inválido ou expirado" },
|
||||||
{ status: 401 },
|
{ status: 401 },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Hash do token para buscar no DB
|
// Buscar token no banco por tokenId para checar revogação
|
||||||
const tokenHash = hashToken(token);
|
|
||||||
|
|
||||||
// Buscar token no banco
|
|
||||||
const tokenRecord = await db.query.apiTokens.findFirst({
|
const tokenRecord = await db.query.apiTokens.findFirst({
|
||||||
where: and(
|
where: and(
|
||||||
eq(apiTokens.tokenHash, tokenHash),
|
eq(apiTokens.id, payload.tokenId),
|
||||||
|
eq(apiTokens.userId, payload.sub),
|
||||||
isNull(apiTokens.revokedAt),
|
isNull(apiTokens.revokedAt),
|
||||||
gt(apiTokens.expiresAt, new Date()),
|
gt(apiTokens.expiresAt, new Date()),
|
||||||
),
|
),
|
||||||
@@ -39,7 +39,7 @@ export async function POST(request: Request) {
|
|||||||
|
|
||||||
if (!tokenRecord) {
|
if (!tokenRecord) {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ valid: false, error: "Token inválido ou revogado" },
|
{ valid: false, error: "Token revogado ou não encontrado" },
|
||||||
{ status: 401 },
|
{ status: 401 },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { version as APP_VERSION } from "@/package.json";
|
|
||||||
import { db } from "@/shared/lib/db";
|
import { db } from "@/shared/lib/db";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -20,7 +19,6 @@ export async function GET() {
|
|||||||
{
|
{
|
||||||
status: "ok",
|
status: "ok",
|
||||||
name: "OpenMonetis",
|
name: "OpenMonetis",
|
||||||
version: APP_VERSION,
|
|
||||||
timestamp: new Date().toISOString(),
|
timestamp: new Date().toISOString(),
|
||||||
},
|
},
|
||||||
{ status: 200 },
|
{ status: 200 },
|
||||||
@@ -33,7 +31,6 @@ export async function GET() {
|
|||||||
{
|
{
|
||||||
status: "error",
|
status: "error",
|
||||||
name: "OpenMonetis",
|
name: "OpenMonetis",
|
||||||
version: APP_VERSION,
|
|
||||||
timestamp: new Date().toISOString(),
|
timestamp: new Date().toISOString(),
|
||||||
message: "Database connection failed",
|
message: "Database connection failed",
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { and, eq, gt, isNull, or } from "drizzle-orm";
|
import { and, eq, gt, isNull } from "drizzle-orm";
|
||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { apiTokens, inboxItems } from "@/db/schema";
|
import { apiTokens, inboxItems } from "@/db/schema";
|
||||||
@@ -63,7 +63,7 @@ export async function POST(request: Request) {
|
|||||||
where: and(
|
where: and(
|
||||||
eq(apiTokens.tokenHash, tokenHash),
|
eq(apiTokens.tokenHash, tokenHash),
|
||||||
isNull(apiTokens.revokedAt),
|
isNull(apiTokens.revokedAt),
|
||||||
or(isNull(apiTokens.expiresAt), gt(apiTokens.expiresAt, new Date())),
|
gt(apiTokens.expiresAt, new Date()),
|
||||||
),
|
),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { and, eq, gt, isNull, or } from "drizzle-orm";
|
import { and, eq, gt, isNull } from "drizzle-orm";
|
||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { apiTokens, inboxItems } from "@/db/schema";
|
import { apiTokens, inboxItems } from "@/db/schema";
|
||||||
@@ -56,7 +56,7 @@ export async function POST(request: Request) {
|
|||||||
where: and(
|
where: and(
|
||||||
eq(apiTokens.tokenHash, tokenHash),
|
eq(apiTokens.tokenHash, tokenHash),
|
||||||
isNull(apiTokens.revokedAt),
|
isNull(apiTokens.revokedAt),
|
||||||
or(isNull(apiTokens.expiresAt), gt(apiTokens.expiresAt, new Date())),
|
gt(apiTokens.expiresAt, new Date()),
|
||||||
),
|
),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import {
|
|||||||
fetchSavedInsights,
|
fetchSavedInsights,
|
||||||
savedInsightsPeriodSchema,
|
savedInsightsPeriodSchema,
|
||||||
} from "@/features/insights/queries";
|
} from "@/features/insights/queries";
|
||||||
import { getUserId } from "@/shared/lib/auth/server";
|
import { getOptionalUserSession } from "@/shared/lib/auth/server";
|
||||||
|
|
||||||
const PRIVATE_RESPONSE_HEADERS = {
|
const PRIVATE_RESPONSE_HEADERS = {
|
||||||
"Cache-Control": "private, no-store",
|
"Cache-Control": "private, no-store",
|
||||||
@@ -25,8 +25,18 @@ export async function GET(request: Request) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const userId = await getUserId();
|
const session = await getOptionalUserSession();
|
||||||
const insights = await fetchSavedInsights(userId, validatedPeriod.data);
|
if (!session?.user) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Não autenticado" },
|
||||||
|
{ status: 401, headers: PRIVATE_RESPONSE_HEADERS },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const insights = await fetchSavedInsights(
|
||||||
|
session.user.id,
|
||||||
|
validatedPeriod.data,
|
||||||
|
);
|
||||||
|
|
||||||
return NextResponse.json(insights, {
|
return NextResponse.json(insights, {
|
||||||
headers: PRIVATE_RESPONSE_HEADERS,
|
headers: PRIVATE_RESPONSE_HEADERS,
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { fetchTransactionAttachments } from "@/features/transactions/attachment-queries";
|
import { fetchTransactionAttachments } from "@/features/transactions/attachment-queries";
|
||||||
import { getUserId } from "@/shared/lib/auth/server";
|
import { getOptionalUserSession } from "@/shared/lib/auth/server";
|
||||||
|
|
||||||
const PRIVATE_RESPONSE_HEADERS = {
|
const PRIVATE_RESPONSE_HEADERS = {
|
||||||
"Cache-Control": "private, no-store",
|
"Cache-Control": "private, no-store",
|
||||||
@@ -10,7 +10,19 @@ export async function GET(
|
|||||||
_request: Request,
|
_request: Request,
|
||||||
{ params }: { params: Promise<{ transactionId: string }> },
|
{ params }: { params: Promise<{ transactionId: string }> },
|
||||||
) {
|
) {
|
||||||
const [userId, { transactionId }] = await Promise.all([getUserId(), params]);
|
const [session, { transactionId }] = await Promise.all([
|
||||||
|
getOptionalUserSession(),
|
||||||
|
params,
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (!session?.user) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Não autenticado" },
|
||||||
|
{ status: 401, headers: PRIVATE_RESPONSE_HEADERS },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const userId = session.user.id;
|
||||||
const attachments = await fetchTransactionAttachments(userId, transactionId);
|
const attachments = await fetchTransactionAttachments(userId, transactionId);
|
||||||
|
|
||||||
return NextResponse.json(attachments, {
|
return NextResponse.json(attachments, {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { fetchInstallmentAnticipations } from "@/features/transactions/anticipation-queries";
|
import { fetchInstallmentAnticipations } from "@/features/transactions/anticipation-queries";
|
||||||
import { getUserId } from "@/shared/lib/auth/server";
|
import { getOptionalUserSession } from "@/shared/lib/auth/server";
|
||||||
|
|
||||||
const PRIVATE_RESPONSE_HEADERS = {
|
const PRIVATE_RESPONSE_HEADERS = {
|
||||||
"Cache-Control": "private, no-store",
|
"Cache-Control": "private, no-store",
|
||||||
@@ -11,7 +11,19 @@ export async function GET(
|
|||||||
{ params }: { params: Promise<{ seriesId: string }> },
|
{ params }: { params: Promise<{ seriesId: string }> },
|
||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
const [userId, { seriesId }] = await Promise.all([getUserId(), params]);
|
const [session, { seriesId }] = await Promise.all([
|
||||||
|
getOptionalUserSession(),
|
||||||
|
params,
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (!session?.user) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Não autenticado" },
|
||||||
|
{ status: 401, headers: PRIVATE_RESPONSE_HEADERS },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const userId = session.user.id;
|
||||||
const anticipations = await fetchInstallmentAnticipations(userId, seriesId);
|
const anticipations = await fetchInstallmentAnticipations(userId, seriesId);
|
||||||
|
|
||||||
return NextResponse.json(anticipations, {
|
return NextResponse.json(anticipations, {
|
||||||
|
|||||||
@@ -6,25 +6,7 @@ export default function robots(): MetadataRoute.Robots {
|
|||||||
{
|
{
|
||||||
userAgent: "*",
|
userAgent: "*",
|
||||||
allow: "/",
|
allow: "/",
|
||||||
disallow: [
|
disallow: "/api/",
|
||||||
"/dashboard",
|
|
||||||
"/transactions",
|
|
||||||
"/accounts",
|
|
||||||
"/cards",
|
|
||||||
"/categories",
|
|
||||||
"/budgets",
|
|
||||||
"/payers",
|
|
||||||
"/notes",
|
|
||||||
"/insights",
|
|
||||||
"/calendar",
|
|
||||||
"/attachments",
|
|
||||||
"/settings",
|
|
||||||
"/reports",
|
|
||||||
"/inbox",
|
|
||||||
"/login",
|
|
||||||
"/signup",
|
|
||||||
"/api/",
|
|
||||||
],
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import type { MetadataRoute } from "next";
|
import type { MetadataRoute } from "next";
|
||||||
|
|
||||||
const BASE_URL = process.env.PUBLIC_DOMAIN
|
const BASE_URL = process.env.PUBLIC_DOMAIN
|
||||||
? `https://${process.env.PUBLIC_DOMAIN}`
|
? `https://${process.env.PUBLIC_DOMAIN.replace(/^https?:\/\//, "")}`
|
||||||
: "https://openmonetis.com";
|
: "https://openmonetis.com";
|
||||||
|
|
||||||
export default function sitemap(): MetadataRoute.Sitemap {
|
export default function sitemap(): MetadataRoute.Sitemap {
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ interface CategoryReportExportProps {
|
|||||||
filters: FilterState;
|
filters: FilterState;
|
||||||
}
|
}
|
||||||
|
|
||||||
const loadXlsx = () => import("xlsx");
|
const loadExcelJS = () => import("exceljs");
|
||||||
|
|
||||||
const loadPdfDeps = async () => {
|
const loadPdfDeps = async () => {
|
||||||
const [{ default: jsPDF }, { default: autoTable }] = await Promise.all([
|
const [{ default: jsPDF }, { default: autoTable }] = await Promise.all([
|
||||||
@@ -134,7 +134,7 @@ export function CategoryReportExport({
|
|||||||
const exportToExcel = async () => {
|
const exportToExcel = async () => {
|
||||||
try {
|
try {
|
||||||
setIsExporting(true);
|
setIsExporting(true);
|
||||||
const XLSX = await loadXlsx();
|
const ExcelJS = await loadExcelJS();
|
||||||
|
|
||||||
// Build data array
|
// Build data array
|
||||||
const headers = [
|
const headers = [
|
||||||
@@ -179,20 +179,32 @@ export function CategoryReportExport({
|
|||||||
totalsRow.push(formatCurrency(data.grandTotal));
|
totalsRow.push(formatCurrency(data.grandTotal));
|
||||||
rows.push(totalsRow);
|
rows.push(totalsRow);
|
||||||
|
|
||||||
// Create worksheet
|
// Create workbook and worksheet
|
||||||
const ws = XLSX.utils.aoa_to_sheet([headers, ...rows]);
|
const workbook = new ExcelJS.Workbook();
|
||||||
|
const ws = workbook.addWorksheet("Relatório de Categorias");
|
||||||
|
|
||||||
|
ws.addRows([headers, ...rows]);
|
||||||
|
|
||||||
// Set column widths
|
// Set column widths
|
||||||
ws["!cols"] = [
|
ws.getColumn(1).width = 20;
|
||||||
{ wch: 20 }, // Category
|
for (let i = 0; i < data.periods.length; i++) {
|
||||||
...data.periods.map(() => ({ wch: 15 })), // Periods
|
ws.getColumn(i + 2).width = 15;
|
||||||
{ wch: 15 }, // Total
|
}
|
||||||
];
|
ws.getColumn(data.periods.length + 2).width = 15;
|
||||||
|
|
||||||
// Create workbook and download
|
// Download
|
||||||
const wb = XLSX.utils.book_new();
|
const buffer = await workbook.xlsx.writeBuffer();
|
||||||
XLSX.utils.book_append_sheet(wb, ws, "Relatório de Categorias");
|
const blob = new Blob([buffer], {
|
||||||
XLSX.writeFile(wb, getFileName("xlsx"));
|
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||||
|
});
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const link = document.createElement("a");
|
||||||
|
link.href = url;
|
||||||
|
link.download = getFileName("xlsx");
|
||||||
|
document.body.appendChild(link);
|
||||||
|
link.click();
|
||||||
|
document.body.removeChild(link);
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
|
||||||
toast.success("Relatório exportado em Excel com sucesso!");
|
toast.success("Relatório exportado em Excel com sucesso!");
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -649,7 +649,7 @@ export async function createApiTokenAction(
|
|||||||
name: validated.name,
|
name: validated.name,
|
||||||
tokenHash,
|
tokenHash,
|
||||||
tokenPrefix,
|
tokenPrefix,
|
||||||
expiresAt: null, // No expiration for now
|
expiresAt: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000), // 1 ano
|
||||||
})
|
})
|
||||||
.returning({ id: apiTokens.id });
|
.returning({ id: apiTokens.id });
|
||||||
|
|
||||||
|
|||||||
@@ -45,10 +45,10 @@ export function UploadZone({ onParsed }: UploadZoneProps) {
|
|||||||
reader.readAsText(file, "windows-1252");
|
reader.readAsText(file, "windows-1252");
|
||||||
} else {
|
} else {
|
||||||
const reader = new FileReader();
|
const reader = new FileReader();
|
||||||
reader.onload = (e) => {
|
reader.onload = async (e) => {
|
||||||
try {
|
try {
|
||||||
const buffer = e.target?.result as ArrayBuffer;
|
const buffer = e.target?.result as ArrayBuffer;
|
||||||
const statement = parseXls(buffer);
|
const statement = await parseXls(buffer);
|
||||||
onParsed(statement);
|
onParsed(statement);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(
|
setError(
|
||||||
@@ -62,8 +62,8 @@ export function UploadZone({ onParsed }: UploadZoneProps) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleDownloadTemplate = () => {
|
const handleDownloadTemplate = async () => {
|
||||||
const bytes = generateXlsTemplate();
|
const bytes = await generateXlsTemplate();
|
||||||
const blob = new Blob([bytes], {
|
const blob = new Blob([bytes], {
|
||||||
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ interface LancamentosExportProps {
|
|||||||
exportContext?: TransactionsExportContext;
|
exportContext?: TransactionsExportContext;
|
||||||
}
|
}
|
||||||
|
|
||||||
const loadXlsx = () => import("xlsx");
|
const loadExcelJS = () => import("exceljs");
|
||||||
|
|
||||||
const loadPdfDeps = async () => {
|
const loadPdfDeps = async () => {
|
||||||
const [{ default: jsPDF }, { default: autoTable }] = await Promise.all([
|
const [{ default: jsPDF }, { default: autoTable }] = await Promise.all([
|
||||||
@@ -158,7 +158,7 @@ export function TransactionsExport({
|
|||||||
try {
|
try {
|
||||||
setIsExporting(true);
|
setIsExporting(true);
|
||||||
const transactions = await loadTransactions();
|
const transactions = await loadTransactions();
|
||||||
const XLSX = await loadXlsx();
|
const ExcelJS = await loadExcelJS();
|
||||||
|
|
||||||
const headers = [
|
const headers = [
|
||||||
"Data",
|
"Data",
|
||||||
@@ -188,23 +188,28 @@ export function TransactionsExport({
|
|||||||
rows.push(row);
|
rows.push(row);
|
||||||
});
|
});
|
||||||
|
|
||||||
const ws = XLSX.utils.aoa_to_sheet([headers, ...rows]);
|
const workbook = new ExcelJS.Workbook();
|
||||||
|
const ws = workbook.addWorksheet("Lançamentos");
|
||||||
|
|
||||||
ws["!cols"] = [
|
ws.addRows([headers, ...rows]);
|
||||||
{ wch: 12 }, // Data
|
|
||||||
{ wch: 42 }, // Nome
|
|
||||||
{ wch: 15 }, // Tipo
|
|
||||||
{ wch: 15 }, // Condição
|
|
||||||
{ wch: 20 }, // Pagamento
|
|
||||||
{ wch: 15 }, // Valor
|
|
||||||
{ wch: 20 }, // Category
|
|
||||||
{ wch: 20 }, // Conta/Cartão
|
|
||||||
{ wch: 20 }, // Payer
|
|
||||||
];
|
|
||||||
|
|
||||||
const wb = XLSX.utils.book_new();
|
const colWidths = [12, 42, 15, 15, 20, 15, 20, 20, 20];
|
||||||
XLSX.utils.book_append_sheet(wb, ws, "Lançamentos");
|
colWidths.forEach((w, i) => {
|
||||||
XLSX.writeFile(wb, getFileName("xlsx"));
|
ws.getColumn(i + 1).width = w;
|
||||||
|
});
|
||||||
|
|
||||||
|
const buffer = await workbook.xlsx.writeBuffer();
|
||||||
|
const blob = new Blob([buffer], {
|
||||||
|
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||||
|
});
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const link = document.createElement("a");
|
||||||
|
link.href = url;
|
||||||
|
link.download = getFileName("xlsx");
|
||||||
|
document.body.appendChild(link);
|
||||||
|
link.click();
|
||||||
|
document.body.removeChild(link);
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
|
||||||
toast.success("Lançamentos exportados em Excel com sucesso!");
|
toast.success("Lançamentos exportados em Excel com sucesso!");
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -1,15 +1,34 @@
|
|||||||
import * as XLSX from "xlsx";
|
import ExcelJS from "exceljs";
|
||||||
import type {
|
import type {
|
||||||
ImportedTransaction,
|
ImportedTransaction,
|
||||||
ImportStatement,
|
ImportStatement,
|
||||||
} from "@/shared/lib/import/types";
|
} from "@/shared/lib/import/types";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Converte serial number do Excel (1900 date system) para ano/mês/dia.
|
||||||
|
* Excel trata 1900 como bissexto (serial 60 = 29/02/1900 inexistente).
|
||||||
|
*/
|
||||||
|
function excelSerialToDate(
|
||||||
|
serial: number,
|
||||||
|
): { y: number; m: number; d: number } | null {
|
||||||
|
if (serial < 1) return null;
|
||||||
|
let adjusted = serial;
|
||||||
|
if (serial > 60) adjusted--;
|
||||||
|
const baseDate = new Date(1899, 11, 31);
|
||||||
|
const date = new Date(baseDate.getTime() + adjusted * 86400000);
|
||||||
|
return {
|
||||||
|
y: date.getFullYear(),
|
||||||
|
m: date.getMonth() + 1,
|
||||||
|
d: date.getDate(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
function parseDateValue(value: unknown): string | null {
|
function parseDateValue(value: unknown): string | null {
|
||||||
if (value == null || value === "") return null;
|
if (value == null || value === "") return null;
|
||||||
|
|
||||||
// Excel date serial number
|
// Excel date serial number
|
||||||
if (typeof value === "number") {
|
if (typeof value === "number") {
|
||||||
const date = XLSX.SSF.parse_date_code(value);
|
const date = excelSerialToDate(value);
|
||||||
if (!date) return null;
|
if (!date) return null;
|
||||||
const y = date.y;
|
const y = date.y;
|
||||||
const m = String(date.m).padStart(2, "0");
|
const m = String(date.m).padStart(2, "0");
|
||||||
@@ -17,6 +36,14 @@ function parseDateValue(value: unknown): string | null {
|
|||||||
return `${y}-${m}-${d}`;
|
return `${y}-${m}-${d}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ExcelJS pode retornar Date objects
|
||||||
|
if (value instanceof Date) {
|
||||||
|
const y = value.getFullYear();
|
||||||
|
const m = String(value.getMonth() + 1).padStart(2, "0");
|
||||||
|
const d = String(value.getDate()).padStart(2, "0");
|
||||||
|
return `${y}-${m}-${d}`;
|
||||||
|
}
|
||||||
|
|
||||||
const str = String(value).trim();
|
const str = String(value).trim();
|
||||||
|
|
||||||
// DD/MM/YYYY
|
// DD/MM/YYYY
|
||||||
@@ -43,52 +70,37 @@ function parseAmountValue(value: unknown): number | null {
|
|||||||
return Number.isNaN(num) ? null : Math.abs(num);
|
return Number.isNaN(num) ? null : Math.abs(num);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function parseXls(buffer: ArrayBuffer): ImportStatement {
|
export async function parseXls(buffer: ArrayBuffer): Promise<ImportStatement> {
|
||||||
const workbook = XLSX.read(new Uint8Array(buffer), {
|
const workbook = new ExcelJS.Workbook();
|
||||||
type: "array",
|
await workbook.xlsx.load(buffer);
|
||||||
cellDates: false,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!workbook.SheetNames.length) {
|
if (workbook.worksheets.length === 0) {
|
||||||
throw new Error("Arquivo sem abas.");
|
throw new Error("Arquivo sem abas.");
|
||||||
}
|
}
|
||||||
|
|
||||||
const sheetName = workbook.SheetNames[0];
|
const sheet = workbook.worksheets[0];
|
||||||
const sheet = workbook.Sheets[sheetName];
|
|
||||||
|
|
||||||
if (!sheet) {
|
if (!sheet || sheet.rowCount < 2) {
|
||||||
throw new Error(`Aba "${sheetName}" não encontrada.`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const range = sheet["!ref"];
|
|
||||||
if (!range) {
|
|
||||||
throw new Error("Planilha vazia (sem intervalo de células).");
|
|
||||||
}
|
|
||||||
|
|
||||||
const rows = XLSX.utils.sheet_to_json<unknown[]>(sheet, {
|
|
||||||
header: 1,
|
|
||||||
defval: "",
|
|
||||||
});
|
|
||||||
|
|
||||||
if (rows.length < 2) {
|
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`Planilha vazia ou sem dados (${rows.length} linha(s) encontrada(s)).`,
|
`Planilha vazia ou sem dados (${sheet?.rowCount ?? 0} linha(s) encontrada(s)).`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const transactions: ImportedTransaction[] = [];
|
const transactions: ImportedTransaction[] = [];
|
||||||
|
|
||||||
for (let i = 1; i < rows.length; i++) {
|
sheet.eachRow((row, rowNumber) => {
|
||||||
const row = rows[i] as unknown[];
|
if (rowNumber === 1) return; // skip header
|
||||||
if (!row || row.every((cell) => cell == null || cell === "")) continue;
|
|
||||||
|
|
||||||
const date = parseDateValue(row[0]);
|
// ExcelJS row.values é 1-indexed (values[0] é undefined)
|
||||||
const description = row[1] != null ? String(row[1]).trim() : "";
|
const values = row.values as unknown[];
|
||||||
const amount = parseAmountValue(row[2]);
|
const date = parseDateValue(values[1]);
|
||||||
const typeRaw = row[3] != null ? String(row[3]).toLowerCase().trim() : "";
|
const description = values[2] != null ? String(values[2]).trim() : "";
|
||||||
|
const amount = parseAmountValue(values[3]);
|
||||||
|
const typeRaw =
|
||||||
|
values[4] != null ? String(values[4]).toLowerCase().trim() : "";
|
||||||
const transactionType = typeRaw === "receita" ? "income" : "expense";
|
const transactionType = typeRaw === "receita" ? "income" : "expense";
|
||||||
|
|
||||||
if (!date || !description || amount === null || amount <= 0) continue;
|
if (!date || !description || amount === null || amount <= 0) return;
|
||||||
|
|
||||||
transactions.push({
|
transactions.push({
|
||||||
externalId: null,
|
externalId: null,
|
||||||
@@ -97,7 +109,7 @@ export function parseXls(buffer: ArrayBuffer): ImportStatement {
|
|||||||
description,
|
description,
|
||||||
transactionType,
|
transactionType,
|
||||||
});
|
});
|
||||||
}
|
});
|
||||||
|
|
||||||
if (transactions.length === 0) {
|
if (transactions.length === 0) {
|
||||||
throw new Error("Nenhuma transação válida encontrada na planilha.");
|
throw new Error("Nenhuma transação válida encontrada na planilha.");
|
||||||
@@ -115,31 +127,31 @@ export function parseXls(buffer: ArrayBuffer): ImportStatement {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function generateXlsTemplate(): ArrayBuffer {
|
export async function generateXlsTemplate(): Promise<ArrayBuffer> {
|
||||||
const wb = XLSX.utils.book_new();
|
const workbook = new ExcelJS.Workbook();
|
||||||
|
const ws = workbook.addWorksheet("Lançamentos");
|
||||||
|
|
||||||
const data = [
|
ws.addRows([
|
||||||
["Data", "Descrição", "Valor", "Tipo"],
|
["Data", "Descrição", "Valor", "Tipo"],
|
||||||
["01/03/2026", "Ingressos São Januário", 160, "despesa"],
|
["01/03/2026", "Ingressos São Januário", 160, "despesa"],
|
||||||
["01/03/2026", "Salário", 3000.0, "receita"],
|
["01/03/2026", "Salário", 3000.0, "receita"],
|
||||||
["01/03/2026", "Posto do Vasco da Gama", 89.9, "despesa"],
|
["01/03/2026", "Posto do Vasco da Gama", 89.9, "despesa"],
|
||||||
];
|
]);
|
||||||
|
|
||||||
const ws = XLSX.utils.aoa_to_sheet(data);
|
ws.getColumn(1).width = 14;
|
||||||
|
ws.getColumn(2).width = 32;
|
||||||
|
ws.getColumn(3).width = 12;
|
||||||
|
ws.getColumn(4).width = 10;
|
||||||
|
|
||||||
ws["!cols"] = [{ wch: 14 }, { wch: 32 }, { wch: 12 }, { wch: 10 }];
|
// Dropdown para coluna Tipo (D2:D100)
|
||||||
|
for (let i = 2; i <= 100; i++) {
|
||||||
|
ws.getCell(`D${i}`).dataValidation = {
|
||||||
|
type: "list",
|
||||||
|
allowBlank: true,
|
||||||
|
formulae: ['"despesa,receita"'],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// Dropdown para coluna Tipo (D2:D1000)
|
const buffer = await workbook.xlsx.writeBuffer();
|
||||||
if (!ws["!dataValidations"]) ws["!dataValidations"] = [];
|
return buffer as ArrayBuffer;
|
||||||
(ws["!dataValidations"] as object[]).push({
|
|
||||||
type: "list",
|
|
||||||
sqref: "D2:D1000",
|
|
||||||
formula1: '"despesa,receita"',
|
|
||||||
showDropDown: false,
|
|
||||||
});
|
|
||||||
|
|
||||||
XLSX.utils.book_append_sheet(wb, ws, "Lançamentos");
|
|
||||||
|
|
||||||
const raw = XLSX.write(wb, { type: "array", bookType: "xlsx" }) as number[];
|
|
||||||
return new Uint8Array(raw).buffer as ArrayBuffer;
|
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user