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;