refactor: atualizar imports para os novos nomes de tabelas

- Atualizar imports em todos os arquivos que usavam os nomes antigos
- Corrigir referências para preferenciasUsuario, insightsSalvos, tokensApi, preLancamentos, antecipacoesParcelas, compartilhamentosPagador
This commit is contained in:
Felipe Coutinho
2026-01-27 14:19:46 +00:00
parent cbfed98882
commit 2eafceb6d3
40 changed files with 241 additions and 352 deletions

View File

@@ -1,14 +1,14 @@
"use server";
import { apiTokens, pagadores } from "@/db/schema";
import { auth } from "@/lib/auth/config";
import { db, schema } from "@/lib/db";
import { PAGADOR_ROLE_ADMIN } from "@/lib/pagadores/constants";
import { createHash, randomBytes } from "node:crypto";
import { and, eq, isNull, ne } from "drizzle-orm";
import { revalidatePath } from "next/cache";
import { headers } from "next/headers";
import { createHash, randomBytes } from "node:crypto";
import { z } from "zod";
import { tokensApi, pagadores } from "@/db/schema";
import { auth } from "@/lib/auth/config";
import { db, schema } from "@/lib/db";
import { PAGADOR_ROLE_ADMIN } from "@/lib/pagadores/constants";
type ActionResponse<T = void> = {
success: boolean;
@@ -373,8 +373,8 @@ export async function updatePreferencesAction(
// Check if preferences exist, if not create them
const existingResult = await db
.select()
.from(schema.userPreferences)
.where(eq(schema.userPreferences.userId, session.user.id))
.from(schema.preferenciasUsuario)
.where(eq(schema.preferenciasUsuario.userId, session.user.id))
.limit(1);
const existing = existingResult[0] || null;
@@ -382,15 +382,15 @@ export async function updatePreferencesAction(
if (existing) {
// Update existing preferences
await db
.update(schema.userPreferences)
.update(schema.preferenciasUsuario)
.set({
disableMagnetlines: validated.disableMagnetlines,
updatedAt: new Date(),
})
.where(eq(schema.userPreferences.userId, session.user.id));
.where(eq(schema.preferenciasUsuario.userId, session.user.id));
} else {
// Create new preferences
await db.insert(schema.userPreferences).values({
await db.insert(schema.preferenciasUsuario).values({
userId: session.user.id,
disableMagnetlines: validated.disableMagnetlines,
});
@@ -463,7 +463,7 @@ export async function createApiTokenAction(
// Save to database
const [newToken] = await db
.insert(apiTokens)
.insert(tokensApi)
.values({
userId: session.user.id,
name: validated.name,
@@ -471,7 +471,7 @@ export async function createApiTokenAction(
tokenPrefix,
expiresAt: null, // No expiration for now
})
.returning({ id: apiTokens.id });
.returning({ id: tokensApi.id });
revalidatePath("/ajustes");
@@ -519,12 +519,12 @@ export async function revokeApiTokenAction(
// Find token and verify ownership
const [existingToken] = await db
.select()
.from(apiTokens)
.from(tokensApi)
.where(
and(
eq(apiTokens.id, validated.tokenId),
eq(apiTokens.userId, session.user.id),
isNull(apiTokens.revokedAt),
eq(tokensApi.id, validated.tokenId),
eq(tokensApi.userId, session.user.id),
isNull(tokensApi.revokedAt),
),
)
.limit(1);
@@ -538,11 +538,11 @@ export async function revokeApiTokenAction(
// Revoke token
await db
.update(apiTokens)
.update(tokensApi)
.set({
revokedAt: new Date(),
})
.where(eq(apiTokens.id, validated.tokenId));
.where(eq(tokensApi.id, validated.tokenId));
revalidatePath("/ajustes");

View File

@@ -1,5 +1,5 @@
import { desc, eq } from "drizzle-orm";
import { apiTokens } from "@/db/schema";
import { tokensApi } from "@/db/schema";
import { db, schema } from "@/lib/db";
export interface UserPreferences {
@@ -29,10 +29,10 @@ export async function fetchUserPreferences(
): Promise<UserPreferences | null> {
const result = await db
.select({
disableMagnetlines: schema.userPreferences.disableMagnetlines,
disableMagnetlines: schema.preferenciasUsuario.disableMagnetlines,
})
.from(schema.userPreferences)
.where(eq(schema.userPreferences.userId, userId))
.from(schema.preferenciasUsuario)
.where(eq(schema.preferenciasUsuario.userId, userId))
.limit(1);
return result[0] || null;
@@ -41,18 +41,18 @@ export async function fetchUserPreferences(
export async function fetchApiTokens(userId: string): Promise<ApiToken[]> {
return db
.select({
id: apiTokens.id,
name: apiTokens.name,
tokenPrefix: apiTokens.tokenPrefix,
lastUsedAt: apiTokens.lastUsedAt,
lastUsedIp: apiTokens.lastUsedIp,
createdAt: apiTokens.createdAt,
expiresAt: apiTokens.expiresAt,
revokedAt: apiTokens.revokedAt,
id: tokensApi.id,
name: tokensApi.name,
tokenPrefix: tokensApi.tokenPrefix,
lastUsedAt: tokensApi.lastUsedAt,
lastUsedIp: tokensApi.lastUsedIp,
createdAt: tokensApi.createdAt,
expiresAt: tokensApi.expiresAt,
revokedAt: tokensApi.revokedAt,
})
.from(apiTokens)
.where(eq(apiTokens.userId, userId))
.orderBy(desc(apiTokens.createdAt));
.from(tokensApi)
.where(eq(tokensApi.userId, userId))
.orderBy(desc(tokensApi.createdAt));
}
export async function fetchAjustesPageData(userId: string) {

View File

@@ -1,7 +1,7 @@
import { and, eq, ilike, isNull, not, or, sql } from "drizzle-orm";
import { cartoes, contas, lancamentos } from "@/db/schema";
import { db } from "@/lib/db";
import { loadLogoOptions } from "@/lib/logo/options";
import { and, eq, ilike, isNull, not, or, sql } from "drizzle-orm";
export type CardData = {
id: string;

View File

@@ -1,9 +1,5 @@
import { Skeleton } from "@/components/ui/skeleton";
/**
* Loading state para a página de categorias
* Layout: Header + Tabs + Grid de cards
*/
export default function CategoriasLoading() {
return (
<main className="flex flex-col items-start gap-6">

View File

@@ -1,8 +1,5 @@
import { Skeleton } from "@/components/ui/skeleton";
/**
* Loading state para a página de contas
*/
export default function ContasLoading() {
return (
<main className="flex flex-col gap-6">

View File

@@ -11,11 +11,11 @@ export async function fetchUserDashboardPreferences(
): Promise<UserDashboardPreferences> {
const result = await db
.select({
disableMagnetlines: schema.userPreferences.disableMagnetlines,
dashboardWidgets: schema.userPreferences.dashboardWidgets,
disableMagnetlines: schema.preferenciasUsuario.disableMagnetlines,
dashboardWidgets: schema.preferenciasUsuario.dashboardWidgets,
})
.from(schema.userPreferences)
.where(eq(schema.userPreferences.userId, userId))
.from(schema.preferenciasUsuario)
.where(eq(schema.preferenciasUsuario.userId, userId))
.limit(1);
return {

View File

@@ -14,7 +14,7 @@ import {
lancamentos,
orcamentos,
pagadores,
savedInsights,
insightsSalvos,
} from "@/db/schema";
import { ACCOUNT_AUTO_INVOICE_NOTE_PREFIX } from "@/lib/accounts/constants";
import { getUser } from "@/lib/auth/server";
@@ -697,11 +697,11 @@ export async function saveInsightsAction(
// Verificar se já existe um insight salvo para este período
const existing = await db
.select()
.from(savedInsights)
.from(insightsSalvos)
.where(
and(
eq(savedInsights.userId, user.id),
eq(savedInsights.period, period),
eq(insightsSalvos.userId, user.id),
eq(insightsSalvos.period, period),
),
)
.limit(1);
@@ -709,7 +709,7 @@ export async function saveInsightsAction(
if (existing.length > 0) {
// Atualizar existente
const updated = await db
.update(savedInsights)
.update(insightsSalvos)
.set({
modelId,
data: JSON.stringify(data),
@@ -717,13 +717,13 @@ export async function saveInsightsAction(
})
.where(
and(
eq(savedInsights.userId, user.id),
eq(savedInsights.period, period),
eq(insightsSalvos.userId, user.id),
eq(insightsSalvos.period, period),
),
)
.returning({
id: savedInsights.id,
createdAt: savedInsights.createdAt,
id: insightsSalvos.id,
createdAt: insightsSalvos.createdAt,
});
const updatedRecord = updated[0];
@@ -745,14 +745,14 @@ export async function saveInsightsAction(
// Criar novo
const result = await db
.insert(savedInsights)
.insert(insightsSalvos)
.values({
userId: user.id,
period,
modelId,
data: JSON.stringify(data),
})
.returning({ id: savedInsights.id, createdAt: savedInsights.createdAt });
.returning({ id: insightsSalvos.id, createdAt: insightsSalvos.createdAt });
const insertedRecord = result[0];
if (!insertedRecord) {
@@ -796,11 +796,11 @@ export async function loadSavedInsightsAction(period: string): Promise<
const result = await db
.select()
.from(savedInsights)
.from(insightsSalvos)
.where(
and(
eq(savedInsights.userId, user.id),
eq(savedInsights.period, period),
eq(insightsSalvos.userId, user.id),
eq(insightsSalvos.period, period),
),
)
.limit(1);
@@ -852,11 +852,11 @@ export async function deleteSavedInsightsAction(
const user = await getUser();
await db
.delete(savedInsights)
.delete(insightsSalvos)
.where(
and(
eq(savedInsights.userId, user.id),
eq(savedInsights.period, period),
eq(insightsSalvos.userId, user.id),
eq(insightsSalvos.period, period),
),
);

View File

@@ -5,7 +5,7 @@ import { revalidatePath } from "next/cache";
import { z } from "zod";
import {
categorias,
installmentAnticipations,
antecipacoesParcelas,
lancamentos,
pagadores,
} from "@/db/schema";
@@ -235,7 +235,7 @@ export async function createInstallmentAnticipationAction(
// 4.2. Criar registro de antecipação
const [anticipation] = await tx
.insert(installmentAnticipations)
.insert(antecipacoesParcelas)
.values({
seriesId: data.seriesId,
anticipationPeriod: data.anticipationPeriod,
@@ -294,43 +294,43 @@ export async function getInstallmentAnticipationsAction(
// Usar query builder ao invés de db.query para evitar problemas de tipagem
const anticipations = await db
.select({
id: installmentAnticipations.id,
seriesId: installmentAnticipations.seriesId,
anticipationPeriod: installmentAnticipations.anticipationPeriod,
anticipationDate: installmentAnticipations.anticipationDate,
id: antecipacoesParcelas.id,
seriesId: antecipacoesParcelas.seriesId,
anticipationPeriod: antecipacoesParcelas.anticipationPeriod,
anticipationDate: antecipacoesParcelas.anticipationDate,
anticipatedInstallmentIds:
installmentAnticipations.anticipatedInstallmentIds,
totalAmount: installmentAnticipations.totalAmount,
installmentCount: installmentAnticipations.installmentCount,
discount: installmentAnticipations.discount,
lancamentoId: installmentAnticipations.lancamentoId,
pagadorId: installmentAnticipations.pagadorId,
categoriaId: installmentAnticipations.categoriaId,
note: installmentAnticipations.note,
userId: installmentAnticipations.userId,
createdAt: installmentAnticipations.createdAt,
antecipacoesParcelas.anticipatedInstallmentIds,
totalAmount: antecipacoesParcelas.totalAmount,
installmentCount: antecipacoesParcelas.installmentCount,
discount: antecipacoesParcelas.discount,
lancamentoId: antecipacoesParcelas.lancamentoId,
pagadorId: antecipacoesParcelas.pagadorId,
categoriaId: antecipacoesParcelas.categoriaId,
note: antecipacoesParcelas.note,
userId: antecipacoesParcelas.userId,
createdAt: antecipacoesParcelas.createdAt,
// Joins
lancamento: lancamentos,
pagador: pagadores,
categoria: categorias,
})
.from(installmentAnticipations)
.from(antecipacoesParcelas)
.leftJoin(
lancamentos,
eq(installmentAnticipations.lancamentoId, lancamentos.id),
eq(antecipacoesParcelas.lancamentoId, lancamentos.id),
)
.leftJoin(pagadores, eq(installmentAnticipations.pagadorId, pagadores.id))
.leftJoin(pagadores, eq(antecipacoesParcelas.pagadorId, pagadores.id))
.leftJoin(
categorias,
eq(installmentAnticipations.categoriaId, categorias.id),
eq(antecipacoesParcelas.categoriaId, categorias.id),
)
.where(
and(
eq(installmentAnticipations.seriesId, validatedSeriesId),
eq(installmentAnticipations.userId, user.id),
eq(antecipacoesParcelas.seriesId, validatedSeriesId),
eq(antecipacoesParcelas.userId, user.id),
),
)
.orderBy(desc(installmentAnticipations.createdAt));
.orderBy(desc(antecipacoesParcelas.createdAt));
return {
success: true,
@@ -356,32 +356,32 @@ export async function cancelInstallmentAnticipationAction(
// 1. Buscar antecipação usando query builder
const anticipationRows = await tx
.select({
id: installmentAnticipations.id,
seriesId: installmentAnticipations.seriesId,
anticipationPeriod: installmentAnticipations.anticipationPeriod,
anticipationDate: installmentAnticipations.anticipationDate,
id: antecipacoesParcelas.id,
seriesId: antecipacoesParcelas.seriesId,
anticipationPeriod: antecipacoesParcelas.anticipationPeriod,
anticipationDate: antecipacoesParcelas.anticipationDate,
anticipatedInstallmentIds:
installmentAnticipations.anticipatedInstallmentIds,
totalAmount: installmentAnticipations.totalAmount,
installmentCount: installmentAnticipations.installmentCount,
discount: installmentAnticipations.discount,
lancamentoId: installmentAnticipations.lancamentoId,
pagadorId: installmentAnticipations.pagadorId,
categoriaId: installmentAnticipations.categoriaId,
note: installmentAnticipations.note,
userId: installmentAnticipations.userId,
createdAt: installmentAnticipations.createdAt,
antecipacoesParcelas.anticipatedInstallmentIds,
totalAmount: antecipacoesParcelas.totalAmount,
installmentCount: antecipacoesParcelas.installmentCount,
discount: antecipacoesParcelas.discount,
lancamentoId: antecipacoesParcelas.lancamentoId,
pagadorId: antecipacoesParcelas.pagadorId,
categoriaId: antecipacoesParcelas.categoriaId,
note: antecipacoesParcelas.note,
userId: antecipacoesParcelas.userId,
createdAt: antecipacoesParcelas.createdAt,
lancamento: lancamentos,
})
.from(installmentAnticipations)
.from(antecipacoesParcelas)
.leftJoin(
lancamentos,
eq(installmentAnticipations.lancamentoId, lancamentos.id),
eq(antecipacoesParcelas.lancamentoId, lancamentos.id),
)
.where(
and(
eq(installmentAnticipations.id, data.anticipationId),
eq(installmentAnticipations.userId, user.id),
eq(antecipacoesParcelas.id, data.anticipationId),
eq(antecipacoesParcelas.userId, user.id),
),
)
.limit(1);
@@ -426,8 +426,8 @@ export async function cancelInstallmentAnticipationAction(
// 6. Deletar registro de antecipação
await tx
.delete(installmentAnticipations)
.where(eq(installmentAnticipations.id, data.anticipationId));
.delete(antecipacoesParcelas)
.where(eq(antecipacoesParcelas.id, data.anticipationId));
});
revalidatePath("/lancamentos");
@@ -454,10 +454,10 @@ export async function getAnticipationDetailsAction(
// Validar anticipationId
const validatedId = uuidSchema("Antecipação").parse(anticipationId);
const anticipation = await db.query.installmentAnticipations.findFirst({
const anticipation = await db.query.antecipacoesParcelas.findFirst({
where: and(
eq(installmentAnticipations.id, validatedId),
eq(installmentAnticipations.userId, user.id),
eq(antecipacoesParcelas.id, validatedId),
eq(antecipacoesParcelas.userId, user.id),
),
with: {
lancamento: true,

View File

@@ -5,7 +5,7 @@ import {
contas,
lancamentos,
pagadores,
pagadorShares,
compartilhamentosPagador,
user as usersTable,
} from "@/db/schema";
import { db } from "@/lib/db";
@@ -23,15 +23,15 @@ export async function fetchPagadorShares(
): Promise<ShareData[]> {
const shareRows = await db
.select({
id: pagadorShares.id,
sharedWithUserId: pagadorShares.sharedWithUserId,
createdAt: pagadorShares.createdAt,
id: compartilhamentosPagador.id,
sharedWithUserId: compartilhamentosPagador.sharedWithUserId,
createdAt: compartilhamentosPagador.createdAt,
userName: usersTable.name,
userEmail: usersTable.email,
})
.from(pagadorShares)
.innerJoin(usersTable, eq(pagadorShares.sharedWithUserId, usersTable.id))
.where(eq(pagadorShares.pagadorId, pagadorId));
.from(compartilhamentosPagador)
.innerJoin(usersTable, eq(compartilhamentosPagador.sharedWithUserId, usersTable.id))
.where(eq(compartilhamentosPagador.pagadorId, pagadorId));
return shareRows.map((share) => ({
id: share.id,
@@ -46,14 +46,14 @@ export async function fetchCurrentUserShare(
pagadorId: string,
userId: string,
): Promise<{ id: string; createdAt: string } | null> {
const shareRow = await db.query.pagadorShares.findFirst({
const shareRow = await db.query.compartilhamentosPagador.findFirst({
columns: {
id: true,
createdAt: true,
},
where: and(
eq(pagadorShares.pagadorId, pagadorId),
eq(pagadorShares.sharedWithUserId, userId),
eq(compartilhamentosPagador.pagadorId, pagadorId),
eq(compartilhamentosPagador.sharedWithUserId, userId),
),
});

View File

@@ -4,7 +4,7 @@ import { randomBytes } from "node:crypto";
import { and, eq } from "drizzle-orm";
import { revalidatePath } from "next/cache";
import { z } from "zod";
import { pagadores, pagadorShares, user } from "@/db/schema";
import { pagadores, compartilhamentosPagador, user } from "@/db/schema";
import { handleActionError, revalidateForEntity } from "@/lib/actions/helpers";
import type { ActionResult } from "@/lib/actions/types";
import { getUser } from "@/lib/auth/server";
@@ -223,10 +223,10 @@ export async function joinPagadorByShareCodeAction(
};
}
const existingShare = await db.query.pagadorShares.findFirst({
const existingShare = await db.query.compartilhamentosPagador.findFirst({
where: and(
eq(pagadorShares.pagadorId, pagadorRow.id),
eq(pagadorShares.sharedWithUserId, user.id),
eq(compartilhamentosPagador.pagadorId, pagadorRow.id),
eq(compartilhamentosPagador.sharedWithUserId, user.id),
),
});
@@ -237,7 +237,7 @@ export async function joinPagadorByShareCodeAction(
};
}
await db.insert(pagadorShares).values({
await db.insert(compartilhamentosPagador).values({
pagadorId: pagadorRow.id,
sharedWithUserId: user.id,
permission: "read",
@@ -259,13 +259,13 @@ export async function deletePagadorShareAction(
const user = await getUser();
const data = shareDeleteSchema.parse(input);
const existing = await db.query.pagadorShares.findFirst({
const existing = await db.query.compartilhamentosPagador.findFirst({
columns: {
id: true,
pagadorId: true,
sharedWithUserId: true,
},
where: eq(pagadorShares.id, data.shareId),
where: eq(compartilhamentosPagador.id, data.shareId),
with: {
pagador: {
columns: {
@@ -287,7 +287,7 @@ export async function deletePagadorShareAction(
};
}
await db.delete(pagadorShares).where(eq(pagadorShares.id, data.shareId));
await db.delete(compartilhamentosPagador).where(eq(compartilhamentosPagador.id, data.shareId));
revalidate();
revalidatePath(`/pagadores/${existing.pagadorId}`);

View File

@@ -3,7 +3,7 @@
import { and, eq, inArray } from "drizzle-orm";
import { revalidatePath } from "next/cache";
import { z } from "zod";
import { inboxItems } from "@/db/schema";
import { preLancamentos } from "@/db/schema";
import { handleActionError } from "@/lib/actions/helpers";
import type { ActionResult } from "@/lib/actions/types";
import { getUser } from "@/lib/auth/server";
@@ -40,12 +40,12 @@ export async function markInboxAsProcessedAction(
// Verificar se item existe e pertence ao usuário
const [item] = await db
.select()
.from(inboxItems)
.from(preLancamentos)
.where(
and(
eq(inboxItems.id, data.inboxItemId),
eq(inboxItems.userId, user.id),
eq(inboxItems.status, "pending"),
eq(preLancamentos.id, data.inboxItemId),
eq(preLancamentos.userId, user.id),
eq(preLancamentos.status, "pending"),
),
)
.limit(1);
@@ -56,13 +56,13 @@ export async function markInboxAsProcessedAction(
// Marcar item como processado
await db
.update(inboxItems)
.update(preLancamentos)
.set({
status: "processed",
processedAt: new Date(),
updatedAt: new Date(),
})
.where(eq(inboxItems.id, data.inboxItemId));
.where(eq(preLancamentos.id, data.inboxItemId));
revalidateInbox();
@@ -82,12 +82,12 @@ export async function discardInboxItemAction(
// Verificar se item existe e pertence ao usuário
const [item] = await db
.select()
.from(inboxItems)
.from(preLancamentos)
.where(
and(
eq(inboxItems.id, data.inboxItemId),
eq(inboxItems.userId, user.id),
eq(inboxItems.status, "pending"),
eq(preLancamentos.id, data.inboxItemId),
eq(preLancamentos.userId, user.id),
eq(preLancamentos.status, "pending"),
),
)
.limit(1);
@@ -98,13 +98,13 @@ export async function discardInboxItemAction(
// Marcar item como descartado
await db
.update(inboxItems)
.update(preLancamentos)
.set({
status: "discarded",
discardedAt: new Date(),
updatedAt: new Date(),
})
.where(eq(inboxItems.id, data.inboxItemId));
.where(eq(preLancamentos.id, data.inboxItemId));
revalidateInbox();
@@ -123,7 +123,7 @@ export async function bulkDiscardInboxItemsAction(
// Marcar todos os itens como descartados
await db
.update(inboxItems)
.update(preLancamentos)
.set({
status: "discarded",
discardedAt: new Date(),
@@ -131,9 +131,9 @@ export async function bulkDiscardInboxItemsAction(
})
.where(
and(
inArray(inboxItems.id, data.inboxItemIds),
eq(inboxItems.userId, user.id),
eq(inboxItems.status, "pending"),
inArray(preLancamentos.id, data.inboxItemIds),
eq(preLancamentos.userId, user.id),
eq(preLancamentos.status, "pending"),
),
);

View File

@@ -1,6 +1,4 @@
/**
* Data fetching functions for Pré-Lançamentos
*/
import { and, desc, eq, gte } from "drizzle-orm";
import type {
@@ -11,7 +9,7 @@ import {
cartoes,
categorias,
contas,
inboxItems,
preLancamentos,
lancamentos,
} from "@/db/schema";
import { db } from "@/lib/db";
@@ -27,9 +25,9 @@ export async function fetchInboxItems(
): Promise<InboxItem[]> {
const items = await db
.select()
.from(inboxItems)
.where(and(eq(inboxItems.userId, userId), eq(inboxItems.status, status)))
.orderBy(desc(inboxItems.createdAt));
.from(preLancamentos)
.where(and(eq(preLancamentos.userId, userId), eq(preLancamentos.status, status)))
.orderBy(desc(preLancamentos.createdAt));
return items;
}
@@ -40,8 +38,8 @@ export async function fetchInboxItemById(
): Promise<InboxItem | null> {
const [item] = await db
.select()
.from(inboxItems)
.where(and(eq(inboxItems.id, itemId), eq(inboxItems.userId, userId)))
.from(preLancamentos)
.where(and(eq(preLancamentos.id, itemId), eq(preLancamentos.userId, userId)))
.limit(1);
return item ?? null;
@@ -90,10 +88,10 @@ export async function fetchCartoesForSelect(
export async function fetchPendingInboxCount(userId: string): Promise<number> {
const items = await db
.select({ id: inboxItems.id })
.from(inboxItems)
.select({ id: preLancamentos.id })
.from(preLancamentos)
.where(
and(eq(inboxItems.userId, userId), eq(inboxItems.status, "pending")),
and(eq(preLancamentos.userId, userId), eq(preLancamentos.status, "pending")),
);
return items.length;

View File

@@ -1,13 +1,8 @@
/**
* POST /api/auth/device/refresh
*
* Atualiza access token usando refresh token.
* Usado pelo app Android quando o access token expira.
*/
import { and, eq, isNull } from "drizzle-orm";
import { NextResponse } from "next/server";
import { apiTokens } from "@/db/schema";
import { tokensApi } from "@/db/schema";
import {
extractBearerToken,
hashToken,
@@ -40,11 +35,11 @@ export async function POST(request: Request) {
}
// Verificar se token não foi revogado
const tokenRecord = await db.query.apiTokens.findFirst({
const tokenRecord = await db.query.tokensApi.findFirst({
where: and(
eq(apiTokens.id, payload.tokenId),
eq(apiTokens.userId, payload.sub),
isNull(apiTokens.revokedAt),
eq(tokensApi.id, payload.tokenId),
eq(tokensApi.userId, payload.sub),
isNull(tokensApi.revokedAt),
),
});
@@ -67,7 +62,7 @@ export async function POST(request: Request) {
// Atualizar hash do token e último uso
await db
.update(apiTokens)
.update(tokensApi)
.set({
tokenHash: hashToken(result.accessToken),
lastUsedAt: new Date(),
@@ -76,7 +71,7 @@ export async function POST(request: Request) {
request.headers.get("x-real-ip"),
expiresAt: result.expiresAt,
})
.where(eq(apiTokens.id, payload.tokenId));
.where(eq(tokensApi.id, payload.tokenId));
return NextResponse.json({
accessToken: result.accessToken,

View File

@@ -1,14 +1,9 @@
/**
* POST /api/auth/device/token
*
* Gera um novo token de API para dispositivo.
* Requer sessão web autenticada.
*/
import { headers } from "next/headers";
import { NextResponse } from "next/server";
import { z } from "zod";
import { apiTokens } from "@/db/schema";
import { tokensApi } from "@/db/schema";
import {
generateTokenPair,
getTokenPrefix,
@@ -42,7 +37,7 @@ export async function POST(request: Request) {
);
// Salvar hash do token no banco
await db.insert(apiTokens).values({
await db.insert(tokensApi).values({
id: tokenId,
userId: session.user.id,
name,

View File

@@ -1,14 +1,9 @@
/**
* DELETE /api/auth/device/tokens/[tokenId]
*
* Revoga um token de API específico.
* Requer sessão web autenticada.
*/
import { and, eq } from "drizzle-orm";
import { headers } from "next/headers";
import { NextResponse } from "next/server";
import { apiTokens } from "@/db/schema";
import { tokensApi } from "@/db/schema";
import { auth } from "@/lib/auth/config";
import { db } from "@/lib/db";
@@ -28,10 +23,10 @@ export async function DELETE(_request: Request, { params }: RouteParams) {
}
// Verificar se token pertence ao usuário
const token = await db.query.apiTokens.findFirst({
const token = await db.query.tokensApi.findFirst({
where: and(
eq(apiTokens.id, tokenId),
eq(apiTokens.userId, session.user.id),
eq(tokensApi.id, tokenId),
eq(tokensApi.userId, session.user.id),
),
});
@@ -44,9 +39,9 @@ export async function DELETE(_request: Request, { params }: RouteParams) {
// Revogar token (soft delete)
await db
.update(apiTokens)
.update(tokensApi)
.set({ revokedAt: new Date() })
.where(eq(apiTokens.id, tokenId));
.where(eq(tokensApi.id, tokenId));
return NextResponse.json({
message: "Token revogado com sucesso",

View File

@@ -1,14 +1,9 @@
/**
* GET /api/auth/device/tokens
*
* Lista todos os tokens de API do usuário.
* Requer sessão web autenticada.
*/
import { desc, eq } from "drizzle-orm";
import { headers } from "next/headers";
import { NextResponse } from "next/server";
import { apiTokens } from "@/db/schema";
import { tokensApi } from "@/db/schema";
import { auth } from "@/lib/auth/config";
import { db } from "@/lib/db";
@@ -24,17 +19,17 @@ export async function GET() {
// Buscar tokens ativos do usuário
const tokens = await db
.select({
id: apiTokens.id,
name: apiTokens.name,
tokenPrefix: apiTokens.tokenPrefix,
lastUsedAt: apiTokens.lastUsedAt,
lastUsedIp: apiTokens.lastUsedIp,
expiresAt: apiTokens.expiresAt,
createdAt: apiTokens.createdAt,
id: tokensApi.id,
name: tokensApi.name,
tokenPrefix: tokensApi.tokenPrefix,
lastUsedAt: tokensApi.lastUsedAt,
lastUsedIp: tokensApi.lastUsedIp,
expiresAt: tokensApi.expiresAt,
createdAt: tokensApi.createdAt,
})
.from(apiTokens)
.where(eq(apiTokens.userId, session.user.id))
.orderBy(desc(apiTokens.createdAt));
.from(tokensApi)
.where(eq(tokensApi.userId, session.user.id))
.orderBy(desc(tokensApi.createdAt));
// Separar tokens ativos e revogados
const activeTokens = tokens.filter(

View File

@@ -1,15 +1,8 @@
/**
* POST /api/auth/device/verify
*
* Valida se um token de API é válido.
* Usado pelo app Android durante o setup.
*
* Aceita tokens no formato os_xxx (hash-based, sem expiração).
*/
import { and, eq, isNull } from "drizzle-orm";
import { NextResponse } from "next/server";
import { apiTokens } from "@/db/schema";
import { tokensApi } from "@/db/schema";
import { extractBearerToken, hashToken } from "@/lib/auth/api-token";
import { db } from "@/lib/db";
@@ -38,10 +31,10 @@ export async function POST(request: Request) {
const tokenHash = hashToken(token);
// Buscar token no banco
const tokenRecord = await db.query.apiTokens.findFirst({
const tokenRecord = await db.query.tokensApi.findFirst({
where: and(
eq(apiTokens.tokenHash, tokenHash),
isNull(apiTokens.revokedAt),
eq(tokensApi.tokenHash, tokenHash),
isNull(tokensApi.revokedAt),
),
});
@@ -59,12 +52,12 @@ export async function POST(request: Request) {
null;
await db
.update(apiTokens)
.update(tokensApi)
.set({
lastUsedAt: new Date(),
lastUsedIp: clientIp,
})
.where(eq(apiTokens.id, tokenRecord.id));
.where(eq(tokensApi.id, tokenRecord.id));
return NextResponse.json({
valid: true,

View File

@@ -1,14 +1,9 @@
/**
* POST /api/inbox/batch
*
* Recebe múltiplas notificações do app Android (sync offline).
* Requer autenticação via API token (formato os_xxx).
*/
import { and, eq, isNull } from "drizzle-orm";
import { NextResponse } from "next/server";
import { z } from "zod";
import { apiTokens, inboxItems } from "@/db/schema";
import { tokensApi, preLancamentos } from "@/db/schema";
import { extractBearerToken, hashToken } from "@/lib/auth/api-token";
import { db } from "@/lib/db";
import { inboxBatchSchema } from "@/lib/schemas/inbox";
@@ -66,10 +61,10 @@ export async function POST(request: Request) {
const tokenHash = hashToken(token);
// Buscar token no banco
const tokenRecord = await db.query.apiTokens.findFirst({
const tokenRecord = await db.query.tokensApi.findFirst({
where: and(
eq(apiTokens.tokenHash, tokenHash),
isNull(apiTokens.revokedAt),
eq(tokensApi.tokenHash, tokenHash),
isNull(tokensApi.revokedAt),
),
});
@@ -98,7 +93,7 @@ export async function POST(request: Request) {
for (const item of items) {
try {
const [inserted] = await db
.insert(inboxItems)
.insert(preLancamentos)
.values({
userId: tokenRecord.userId,
sourceApp: item.sourceApp,
@@ -111,7 +106,7 @@ export async function POST(request: Request) {
parsedTransactionType: item.parsedTransactionType,
status: "pending",
})
.returning({ id: inboxItems.id });
.returning({ id: preLancamentos.id });
results.push({
clientId: item.clientId,
@@ -134,12 +129,12 @@ export async function POST(request: Request) {
null;
await db
.update(apiTokens)
.update(tokensApi)
.set({
lastUsedAt: new Date(),
lastUsedIp: clientIp,
})
.where(eq(apiTokens.id, tokenRecord.id));
.where(eq(tokensApi.id, tokenRecord.id));
const successCount = results.filter((r) => r.success).length;
const failCount = results.filter((r) => !r.success).length;

View File

@@ -1,14 +1,9 @@
/**
* POST /api/inbox
*
* Recebe uma notificação do app Android.
* Requer autenticação via API token (formato os_xxx).
*/
import { and, eq, isNull } from "drizzle-orm";
import { NextResponse } from "next/server";
import { z } from "zod";
import { apiTokens, inboxItems } from "@/db/schema";
import { tokensApi, preLancamentos } from "@/db/schema";
import { extractBearerToken, hashToken } from "@/lib/auth/api-token";
import { db } from "@/lib/db";
import { inboxItemSchema } from "@/lib/schemas/inbox";
@@ -59,10 +54,10 @@ export async function POST(request: Request) {
const tokenHash = hashToken(token);
// Buscar token no banco
const tokenRecord = await db.query.apiTokens.findFirst({
const tokenRecord = await db.query.tokensApi.findFirst({
where: and(
eq(apiTokens.tokenHash, tokenHash),
isNull(apiTokens.revokedAt),
eq(tokensApi.tokenHash, tokenHash),
isNull(tokensApi.revokedAt),
),
});
@@ -87,7 +82,7 @@ export async function POST(request: Request) {
// Inserir item na inbox
const [inserted] = await db
.insert(inboxItems)
.insert(preLancamentos)
.values({
userId: tokenRecord.userId,
sourceApp: data.sourceApp,
@@ -100,7 +95,7 @@ export async function POST(request: Request) {
parsedTransactionType: data.parsedTransactionType,
status: "pending",
})
.returning({ id: inboxItems.id });
.returning({ id: preLancamentos.id });
// Atualizar último uso do token
const clientIp =
@@ -109,12 +104,12 @@ export async function POST(request: Request) {
null;
await db
.update(apiTokens)
.update(tokensApi)
.set({
lastUsedAt: new Date(),
lastUsedIp: clientIp,
})
.where(eq(apiTokens.id, tokenRecord.id));
.where(eq(tokensApi.id, tokenRecord.id));
return NextResponse.json(
{

View File

@@ -1,6 +1,4 @@
/**
* Types for Pré-Lançamentos feature
*/
import type { SelectOption as LancamentoSelectOption } from "@/components/lancamentos/types";

View File

@@ -1,8 +1,4 @@
/**
* API Token utilities for OpenSheets Companion
*
* Handles JWT generation, validation, and token hashing for device authentication.
*/
import crypto from "node:crypto";

View File

@@ -1,9 +1,4 @@
/**
* Better Auth Configuration
*
* Configuração central de autenticação usando Better Auth.
* Suporta email/password e Google OAuth.
*/
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";

View File

@@ -1,14 +1,4 @@
/**
* Server-side authentication utilities
*
* This module consolidates server-side auth functions from:
* - /lib/get-user.tsx
* - /lib/get-user-id.tsx
* - /lib/get-user-session.tsx
*
* All functions in this module are server-side only and will redirect
* to /login if the user is not authenticated.
*/
import { headers } from "next/headers";
import { redirect } from "next/navigation";

View File

@@ -1,9 +1,4 @@
/**
* Category defaults and seeding
*
* Consolidated from:
* - /lib/category-defaults.ts
*/
import { eq } from "drizzle-orm";
import { categorias } from "@/db/schema";

View File

@@ -1,6 +1,4 @@
/**
* Common utilities and helpers for dashboard queries
*/
import { calculatePercentageChange } from "@/lib/utils/math";
import { safeToNumber } from "@/lib/utils/number";

View File

@@ -18,21 +18,21 @@ export async function updateWidgetPreferences(
// Check if preferences exist
const existing = await db
.select({ id: schema.userPreferences.id })
.from(schema.userPreferences)
.where(eq(schema.userPreferences.userId, user.id))
.select({ id: schema.preferenciasUsuario.id })
.from(schema.preferenciasUsuario)
.where(eq(schema.preferenciasUsuario.userId, user.id))
.limit(1);
if (existing.length > 0) {
await db
.update(schema.userPreferences)
.update(schema.preferenciasUsuario)
.set({
dashboardWidgets: preferences,
updatedAt: new Date(),
})
.where(eq(schema.userPreferences.userId, user.id));
.where(eq(schema.preferenciasUsuario.userId, user.id));
} else {
await db.insert(schema.userPreferences).values({
await db.insert(schema.preferenciasUsuario).values({
userId: user.id,
dashboardWidgets: preferences,
});
@@ -54,12 +54,12 @@ export async function resetWidgetPreferences(): Promise<{
const user = await getUser();
await db
.update(schema.userPreferences)
.update(schema.preferenciasUsuario)
.set({
dashboardWidgets: null,
updatedAt: new Date(),
})
.where(eq(schema.userPreferences.userId, user.id));
.where(eq(schema.preferenciasUsuario.userId, user.id));
revalidatePath("/dashboard");
return { success: true };
@@ -74,9 +74,9 @@ export async function getWidgetPreferences(): Promise<WidgetPreferences | null>
const user = await getUser();
const result = await db
.select({ dashboardWidgets: schema.userPreferences.dashboardWidgets })
.from(schema.userPreferences)
.where(eq(schema.userPreferences.userId, user.id))
.select({ dashboardWidgets: schema.preferenciasUsuario.dashboardWidgets })
.from(schema.preferenciasUsuario)
.where(eq(schema.preferenciasUsuario.userId, user.id))
.limit(1);
return result[0]?.dashboardWidgets ?? null;

View File

@@ -1,6 +1,6 @@
import type {
AntecipacaoParcela,
Categoria,
InstallmentAnticipation,
Lancamento,
Pagador,
} from "@/db/schema";
@@ -25,7 +25,7 @@ export type EligibleInstallment = {
/**
* Antecipação com dados completos
*/
export type InstallmentAnticipationWithRelations = InstallmentAnticipation & {
export type InstallmentAnticipationWithRelations = AntecipacaoParcela & {
lancamento: Lancamento;
pagador: Pagador | null;
categoria: Categoria | null;

View File

@@ -1,6 +1,4 @@
/**
* Categoria grouping and sorting helpers for lancamentos
*/
import type { SelectOption } from "@/components/lancamentos/types";

View File

@@ -1,6 +1,4 @@
/**
* Form state management helpers for lancamentos
*/
import type { LancamentoItem } from "@/components/lancamentos/types";
import { getTodayDateString } from "@/lib/utils/date";

View File

@@ -1,9 +1,4 @@
/**
* Logo options loader
*
* Consolidated from:
* - /lib/logo-options.ts (async logo loading)
*/
import { readdir } from "node:fs/promises";
import path from "node:path";

View File

@@ -1,5 +1,5 @@
import { and, eq } from "drizzle-orm";
import { pagadores, pagadorShares, user as usersTable } from "@/db/schema";
import { pagadores, compartilhamentosPagador, user as usersTable } from "@/db/schema";
import { db } from "@/lib/db";
export type PagadorWithAccess = typeof pagadores.$inferSelect & {
@@ -18,15 +18,15 @@ export async function fetchPagadoresWithAccess(
}),
db
.select({
shareId: pagadorShares.id,
shareId: compartilhamentosPagador.id,
pagador: pagadores,
ownerName: usersTable.name,
ownerEmail: usersTable.email,
})
.from(pagadorShares)
.innerJoin(pagadores, eq(pagadorShares.pagadorId, pagadores.id))
.from(compartilhamentosPagador)
.innerJoin(pagadores, eq(compartilhamentosPagador.pagadorId, pagadores.id))
.leftJoin(usersTable, eq(pagadores.userId, usersTable.id))
.where(eq(pagadorShares.sharedWithUserId, userId)),
.where(eq(compartilhamentosPagador.sharedWithUserId, userId)),
]);
const ownedMapped: PagadorWithAccess[] = owned.map((item) => ({
@@ -62,14 +62,14 @@ export async function getPagadorAccess(userId: string, pagadorId: string) {
return {
pagador,
canEdit: true,
share: null as typeof pagadorShares.$inferSelect | null,
share: null as typeof compartilhamentosPagador.$inferSelect | null,
};
}
const share = await db.query.pagadorShares.findFirst({
const share = await db.query.compartilhamentosPagador.findFirst({
where: and(
eq(pagadorShares.pagadorId, pagadorId),
eq(pagadorShares.sharedWithUserId, userId),
eq(compartilhamentosPagador.pagadorId, pagadorId),
eq(compartilhamentosPagador.sharedWithUserId, userId),
),
});

View File

@@ -1,9 +1,3 @@
/**
* Pagador constants
*
* Extracted from /lib/pagadores.ts
*/
export const PAGADOR_STATUS_OPTIONS = ["Ativo", "Inativo"] as const;
export type PagadorStatus = (typeof PAGADOR_STATUS_OPTIONS)[number];

View File

@@ -1,9 +1,3 @@
/**
* Pagador defaults - User seeding logic
*
* Moved from /lib/pagador-defaults.ts to /lib/pagadores/defaults.ts
*/
import { eq } from "drizzle-orm";
import { pagadores } from "@/db/schema";
import { db } from "@/lib/db";

View File

@@ -1,6 +1,3 @@
import { cartoes, lancamentos } from "@/db/schema";
import { ACCOUNT_AUTO_INVOICE_NOTE_PREFIX } from "@/lib/accounts/constants";
import { db } from "@/lib/db";
import {
and,
eq,
@@ -13,6 +10,9 @@ import {
sql,
sum,
} from "drizzle-orm";
import { cartoes, lancamentos } from "@/db/schema";
import { ACCOUNT_AUTO_INVOICE_NOTE_PREFIX } from "@/lib/accounts/constants";
import { db } from "@/lib/db";
const RECEITA = "Receita";
const DESPESA = "Despesa";

View File

@@ -1,8 +1,4 @@
/**
* Pagador utility functions
*
* Extracted from /lib/pagadores.ts
*/
import { DEFAULT_PAGADOR_AVATAR } from "./constants";

View File

@@ -1,6 +1,4 @@
/**
* Data fetching function for Category Chart (based on selected filters)
*/
import { format } from "date-fns";
import { ptBR } from "date-fns/locale";

View File

@@ -1,6 +1,4 @@
/**
* Data fetching function for Category Report
*/
import { and, eq, inArray, isNull, or, sql } from "drizzle-orm";
import { categorias, lancamentos, pagadores } from "@/db/schema";

View File

@@ -1,6 +1,4 @@
/**
* Utility functions for Category Report feature
*/
import { currencyFormatter } from "@/lib/lancamentos/formatting-helpers";
import { calculatePercentageChange } from "@/lib/utils/math";

View File

@@ -1,6 +1,4 @@
/**
* Zod schemas for inbox items (OpenSheets Companion)
*/
import { z } from "zod";

View File

@@ -1,8 +1,4 @@
/**
* UI utilities - Functions for UI manipulation and styling
*
* This module contains UI-related utilities, primarily for className manipulation.
*/
import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";