refactor(inbox): rename caixa-de-entrada to pre-lancamentos e remove colunas não utilizadas

BREAKING CHANGES:
- Renomeia rota /caixa-de-entrada para /pre-lancamentos
- Remove colunas device_id, parsed_date e discard_reason da tabela inbox_items

Mudanças:
- Move componentes de caixa-de-entrada para pre-lancamentos
- Atualiza sidebar e navegação para nova rota
- Remove campos não utilizados do schema, types e APIs
- Adiciona migration 0011 para remover colunas do banco
- Simplifica lógica de data padrão usando notificationTimestamp
This commit is contained in:
Felipe Coutinho
2026-01-26 17:05:55 +00:00
parent c0fb11f89c
commit 8ffe61c59b
23 changed files with 2606 additions and 272 deletions

View File

@@ -0,0 +1,149 @@
"use server";
import { inboxItems } from "@/db/schema";
import { handleActionError } from "@/lib/actions/helpers";
import type { ActionResult } from "@/lib/actions/types";
import { getUser } from "@/lib/auth/server";
import { db } from "@/lib/db";
import { and, eq, inArray } from "drizzle-orm";
import { revalidatePath } from "next/cache";
import { z } from "zod";
const markProcessedSchema = z.object({
inboxItemId: z.string().uuid("ID do item inválido"),
});
const discardInboxSchema = z.object({
inboxItemId: z.string().uuid("ID do item inválido"),
});
const bulkDiscardSchema = z.object({
inboxItemIds: z.array(z.string().uuid()).min(1, "Selecione ao menos um item"),
});
function revalidateInbox() {
revalidatePath("/pre-lancamentos");
revalidatePath("/lancamentos");
revalidatePath("/dashboard");
}
/**
* Mark an inbox item as processed after a lancamento was created
*/
export async function markInboxAsProcessedAction(
input: z.infer<typeof markProcessedSchema>,
): Promise<ActionResult> {
try {
const user = await getUser();
const data = markProcessedSchema.parse(input);
// Verificar se item existe e pertence ao usuário
const [item] = await db
.select()
.from(inboxItems)
.where(
and(
eq(inboxItems.id, data.inboxItemId),
eq(inboxItems.userId, user.id),
eq(inboxItems.status, "pending"),
),
)
.limit(1);
if (!item) {
return { success: false, error: "Item não encontrado ou já processado." };
}
// Marcar item como processado
await db
.update(inboxItems)
.set({
status: "processed",
processedAt: new Date(),
updatedAt: new Date(),
})
.where(eq(inboxItems.id, data.inboxItemId));
revalidateInbox();
return { success: true, message: "Item processado com sucesso!" };
} catch (error) {
return handleActionError(error);
}
}
export async function discardInboxItemAction(
input: z.infer<typeof discardInboxSchema>,
): Promise<ActionResult> {
try {
const user = await getUser();
const data = discardInboxSchema.parse(input);
// Verificar se item existe e pertence ao usuário
const [item] = await db
.select()
.from(inboxItems)
.where(
and(
eq(inboxItems.id, data.inboxItemId),
eq(inboxItems.userId, user.id),
eq(inboxItems.status, "pending"),
),
)
.limit(1);
if (!item) {
return { success: false, error: "Item não encontrado ou já processado." };
}
// Marcar item como descartado
await db
.update(inboxItems)
.set({
status: "discarded",
discardedAt: new Date(),
updatedAt: new Date(),
})
.where(eq(inboxItems.id, data.inboxItemId));
revalidateInbox();
return { success: true, message: "Item descartado." };
} catch (error) {
return handleActionError(error);
}
}
export async function bulkDiscardInboxItemsAction(
input: z.infer<typeof bulkDiscardSchema>,
): Promise<ActionResult> {
try {
const user = await getUser();
const data = bulkDiscardSchema.parse(input);
// Marcar todos os itens como descartados
await db
.update(inboxItems)
.set({
status: "discarded",
discardedAt: new Date(),
updatedAt: new Date(),
})
.where(
and(
inArray(inboxItems.id, data.inboxItemIds),
eq(inboxItems.userId, user.id),
eq(inboxItems.status, "pending"),
),
);
revalidateInbox();
return {
success: true,
message: `${data.inboxItemIds.length} item(s) descartado(s).`,
};
} catch (error) {
return handleActionError(error);
}
}

View File

@@ -0,0 +1,154 @@
/**
* Data fetching functions for Pré-Lançamentos
*/
import { db } from "@/lib/db";
import { inboxItems, categorias, contas, cartoes, lancamentos } from "@/db/schema";
import { eq, desc, and, gte } from "drizzle-orm";
import type { InboxItem, SelectOption } from "@/components/pre-lancamentos/types";
import {
fetchLancamentoFilterSources,
buildSluggedFilters,
buildOptionSets,
} from "@/lib/lancamentos/page-helpers";
export async function fetchInboxItems(
userId: string,
status: "pending" | "processed" | "discarded" = "pending"
): Promise<InboxItem[]> {
const items = await db
.select()
.from(inboxItems)
.where(and(eq(inboxItems.userId, userId), eq(inboxItems.status, status)))
.orderBy(desc(inboxItems.createdAt));
return items;
}
export async function fetchInboxItemById(
userId: string,
itemId: string
): Promise<InboxItem | null> {
const [item] = await db
.select()
.from(inboxItems)
.where(and(eq(inboxItems.id, itemId), eq(inboxItems.userId, userId)))
.limit(1);
return item ?? null;
}
export async function fetchCategoriasForSelect(
userId: string,
type?: string
): Promise<SelectOption[]> {
const query = db
.select({ id: categorias.id, name: categorias.name })
.from(categorias)
.where(
type
? and(eq(categorias.userId, userId), eq(categorias.type, type))
: eq(categorias.userId, userId)
)
.orderBy(categorias.name);
return query;
}
export async function fetchContasForSelect(userId: string): Promise<SelectOption[]> {
const items = await db
.select({ id: contas.id, name: contas.name })
.from(contas)
.where(and(eq(contas.userId, userId), eq(contas.status, "ativo")))
.orderBy(contas.name);
return items;
}
export async function fetchCartoesForSelect(
userId: string
): Promise<(SelectOption & { lastDigits?: string })[]> {
const items = await db
.select({ id: cartoes.id, name: cartoes.name })
.from(cartoes)
.where(and(eq(cartoes.userId, userId), eq(cartoes.status, "ativo")))
.orderBy(cartoes.name);
return items;
}
export async function fetchPendingInboxCount(userId: string): Promise<number> {
const items = await db
.select({ id: inboxItems.id })
.from(inboxItems)
.where(and(eq(inboxItems.userId, userId), eq(inboxItems.status, "pending")));
return items.length;
}
/**
* Fetch all data needed for the LancamentoDialog in inbox context
*/
export async function fetchInboxDialogData(userId: string): Promise<{
pagadorOptions: SelectOption[];
splitPagadorOptions: SelectOption[];
defaultPagadorId: string | null;
contaOptions: SelectOption[];
cartaoOptions: SelectOption[];
categoriaOptions: SelectOption[];
estabelecimentos: string[];
}> {
const filterSources = await fetchLancamentoFilterSources(userId);
const sluggedFilters = buildSluggedFilters(filterSources);
const {
pagadorOptions,
splitPagadorOptions,
defaultPagadorId,
contaOptions,
cartaoOptions,
categoriaOptions,
} = buildOptionSets({
...sluggedFilters,
pagadorRows: filterSources.pagadorRows,
});
// Fetch recent establishments (same approach as getRecentEstablishmentsAction)
const threeMonthsAgo = new Date();
threeMonthsAgo.setMonth(threeMonthsAgo.getMonth() - 3);
const recentEstablishments = await db
.select({ name: lancamentos.name })
.from(lancamentos)
.where(
and(
eq(lancamentos.userId, userId),
gte(lancamentos.purchaseDate, threeMonthsAgo)
)
)
.orderBy(desc(lancamentos.purchaseDate));
// Remove duplicates and filter empty names
const filteredNames: string[] = recentEstablishments
.map((r: { name: string }) => r.name)
.filter(
(name: string | null): name is string =>
name != null &&
name.trim().length > 0 &&
!name.toLowerCase().startsWith("pagamento fatura")
);
const estabelecimentos = Array.from<string>(new Set(filteredNames)).slice(
0,
100
);
return {
pagadorOptions,
splitPagadorOptions,
defaultPagadorId,
contaOptions,
cartaoOptions,
categoriaOptions,
estabelecimentos,
};
}

View File

@@ -0,0 +1,23 @@
import PageDescription from "@/components/page-description";
import { RiInboxLine } from "@remixicon/react";
export const metadata = {
title: "Pré-Lançamentos | Opensheets",
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<section className="space-y-6 px-6">
<PageDescription
icon={<RiInboxLine />}
title="Pré-Lançamentos"
subtitle="Notificações capturadas aguardando processamento"
/>
{children}
</section>
);
}

View File

@@ -0,0 +1,33 @@
import { Card } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
export default function Loading() {
return (
<main className="flex flex-col items-start gap-6">
<div className="flex w-full flex-col gap-6">
<div className="flex justify-between">
<Skeleton className="h-10 w-48" />
<Skeleton className="h-10 w-32" />
</div>
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
{Array.from({ length: 6 }).map((_, i) => (
<Card key={i} className="p-4">
<div className="space-y-3">
<div className="flex justify-between">
<Skeleton className="h-5 w-24" />
<Skeleton className="h-5 w-16" />
</div>
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-3/4" />
<div className="flex gap-2 pt-2">
<Skeleton className="h-8 w-20" />
<Skeleton className="h-8 w-20" />
</div>
</div>
</Card>
))}
</div>
</div>
</main>
);
}

View File

@@ -0,0 +1,27 @@
import { InboxPage } from "@/components/pre-lancamentos/inbox-page";
import { getUserId } from "@/lib/auth/server";
import { fetchInboxDialogData, fetchInboxItems } from "./data";
export default async function Page() {
const userId = await getUserId();
const [items, dialogData] = await Promise.all([
fetchInboxItems(userId, "pending"),
fetchInboxDialogData(userId),
]);
return (
<main className="flex flex-col items-start gap-6">
<InboxPage
items={items}
pagadorOptions={dialogData.pagadorOptions}
splitPagadorOptions={dialogData.splitPagadorOptions}
defaultPagadorId={dialogData.defaultPagadorId}
contaOptions={dialogData.contaOptions}
cartaoOptions={dialogData.cartaoOptions}
categoriaOptions={dialogData.categoriaOptions}
estabelecimentos={dialogData.estabelecimentos}
/>
</main>
);
}