Adicionado aba de estabelecimentos e feita ajuste de interface. Detalhes adicionados no CHANGELOG.md

This commit is contained in:
Guilherme Bano
2026-02-20 00:39:50 -03:00
committed by Felipe Coutinho
parent ffde55f589
commit 9b78f839bf
23 changed files with 695 additions and 55 deletions

View File

@@ -0,0 +1,102 @@
"use server";
import { and, eq } from "drizzle-orm";
import { z } from "zod";
import { estabelecimentos, lancamentos } from "@/db/schema";
import {
type ActionResult,
handleActionError,
revalidateForEntity,
} from "@/lib/actions/helpers";
import { getUser } from "@/lib/auth/server";
import { db } from "@/lib/db";
import { uuidSchema } from "@/lib/schemas/common";
const createSchema = z.object({
name: z
.string({ message: "Informe o nome do estabelecimento." })
.trim()
.min(1, "Informe o nome do estabelecimento."),
});
const deleteSchema = z.object({
id: uuidSchema("Estabelecimento"),
});
export async function createEstabelecimentoAction(
input: z.infer<typeof createSchema>,
): Promise<ActionResult> {
try {
const user = await getUser();
const data = createSchema.parse(input);
await db.insert(estabelecimentos).values({
name: data.name,
userId: user.id,
});
revalidateForEntity("estabelecimentos");
return { success: true, message: "Estabelecimento criado com sucesso." };
} catch (error) {
return handleActionError(error);
}
}
export async function deleteEstabelecimentoAction(
input: z.infer<typeof deleteSchema>,
): Promise<ActionResult> {
try {
const user = await getUser();
const data = deleteSchema.parse(input);
const row = await db.query.estabelecimentos.findFirst({
columns: { id: true, name: true },
where: and(
eq(estabelecimentos.id, data.id),
eq(estabelecimentos.userId, user.id),
),
});
if (!row) {
return {
success: false,
error: "Estabelecimento não encontrado.",
};
}
const [linked] = await db
.select({ id: lancamentos.id })
.from(lancamentos)
.where(
and(
eq(lancamentos.userId, user.id),
eq(lancamentos.name, row.name),
),
)
.limit(1);
if (linked) {
return {
success: false,
error:
"Não é possível excluir: existem lançamentos vinculados a este estabelecimento. Remova ou altere os lançamentos primeiro.",
};
}
await db
.delete(estabelecimentos)
.where(
and(
eq(estabelecimentos.id, data.id),
eq(estabelecimentos.userId, user.id),
),
);
revalidateForEntity("estabelecimentos");
return { success: true, message: "Estabelecimento excluído com sucesso." };
} catch (error) {
return handleActionError(error);
}
}

View File

@@ -0,0 +1,66 @@
import { count, eq } from "drizzle-orm";
import { estabelecimentos, lancamentos } from "@/db/schema";
import { db } from "@/lib/db";
export type EstabelecimentoRow = {
name: string;
lancamentosCount: number;
estabelecimentoId: string | null;
};
export async function fetchEstabelecimentosForUser(
userId: string,
): Promise<EstabelecimentoRow[]> {
const [countsByName, estabelecimentosRows] = await Promise.all([
db
.select({
name: lancamentos.name,
count: count().as("count"),
})
.from(lancamentos)
.where(eq(lancamentos.userId, userId))
.groupBy(lancamentos.name),
db.query.estabelecimentos.findMany({
columns: { id: true, name: true },
where: eq(estabelecimentos.userId, userId),
}),
]);
const map = new Map<
string,
{ lancamentosCount: number; estabelecimentoId: string | null }
>();
for (const row of countsByName) {
const name = row.name?.trim();
if (name == null || name.length === 0) continue;
map.set(name, {
lancamentosCount: Number(row.count ?? 0),
estabelecimentoId: null,
});
}
for (const row of estabelecimentosRows) {
const name = row.name?.trim();
if (name == null || name.length === 0) continue;
const existing = map.get(name);
if (existing) {
existing.estabelecimentoId = row.id;
} else {
map.set(name, {
lancamentosCount: 0,
estabelecimentoId: row.id,
});
}
}
return Array.from(map.entries())
.map(([name, data]) => ({
name,
lancamentosCount: data.lancamentosCount,
estabelecimentoId: data.estabelecimentoId,
}))
.sort((a, b) =>
a.name.localeCompare(b.name, "pt-BR", { sensitivity: "base" }),
);
}

View File

@@ -0,0 +1,23 @@
import { RiStore2Line } from "@remixicon/react";
import PageDescription from "@/components/page-description";
export const metadata = {
title: "Estabelecimentos | OpenMonetis",
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<section className="space-y-6 px-6">
<PageDescription
icon={<RiStore2Line />}
title="Estabelecimentos"
subtitle="Gerencie os estabelecimentos dos seus lançamentos. Crie novos, exclua os que não têm lançamentos vinculados e abra o que está vinculado a cada um."
/>
{children}
</section>
);
}

View File

@@ -0,0 +1,19 @@
import { Skeleton } from "@/components/ui/skeleton";
export default function Loading() {
return (
<div className="flex w-full flex-col gap-6">
<div className="flex justify-start">
<Skeleton className="h-10 w-[200px]" />
</div>
<div className="rounded-md border">
<div className="flex flex-col gap-3 p-4">
<Skeleton className="h-10 w-full" />
<Skeleton className="h-12 w-full" />
<Skeleton className="h-12 w-full" />
<Skeleton className="h-12 w-full" />
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,14 @@
import { EstabelecimentosPage } from "@/components/estabelecimentos/estabelecimentos-page";
import { getUserId } from "@/lib/auth/server";
import { fetchEstabelecimentosForUser } from "./data";
export default async function Page() {
const userId = await getUserId();
const rows = await fetchEstabelecimentosForUser(userId);
return (
<main className="flex flex-col items-start gap-6">
<EstabelecimentosPage rows={rows} />
</main>
);
}