Adicionado aba de estabelecimentos e feita ajuste de interface. Detalhes adicionados no CHANGELOG.md
This commit is contained in:
committed by
Felipe Coutinho
parent
ffde55f589
commit
9b78f839bf
@@ -22,7 +22,8 @@ import { noteSchema, uuidSchema } from "@/lib/schemas/common";
|
||||
import {
|
||||
TRANSFER_CATEGORY_NAME,
|
||||
TRANSFER_CONDITION,
|
||||
TRANSFER_ESTABLISHMENT,
|
||||
TRANSFER_ESTABLISHMENT_ENTRADA,
|
||||
TRANSFER_ESTABLISHMENT_SAIDA,
|
||||
TRANSFER_PAYMENT_METHOD,
|
||||
} from "@/lib/transferencias/constants";
|
||||
import { formatDecimalForDbRequired } from "@/lib/utils/currency";
|
||||
@@ -341,12 +342,14 @@ export async function transferBetweenAccountsAction(
|
||||
);
|
||||
}
|
||||
|
||||
const transferNote = `de ${fromAccount.name} -> ${toAccount.name}`;
|
||||
|
||||
// Create outgoing transaction (transfer from source account)
|
||||
await tx.insert(lancamentos).values({
|
||||
condition: TRANSFER_CONDITION,
|
||||
name: `${TRANSFER_ESTABLISHMENT} → ${toAccount.name}`,
|
||||
name: TRANSFER_ESTABLISHMENT_SAIDA,
|
||||
paymentMethod: TRANSFER_PAYMENT_METHOD,
|
||||
note: `Transferência para ${toAccount.name}`,
|
||||
note: transferNote,
|
||||
amount: formatDecimalForDbRequired(-Math.abs(data.amount)),
|
||||
purchaseDate: data.date,
|
||||
transactionType: "Transferência",
|
||||
@@ -362,9 +365,9 @@ export async function transferBetweenAccountsAction(
|
||||
// Create incoming transaction (transfer to destination account)
|
||||
await tx.insert(lancamentos).values({
|
||||
condition: TRANSFER_CONDITION,
|
||||
name: `${TRANSFER_ESTABLISHMENT} ← ${fromAccount.name}`,
|
||||
name: TRANSFER_ESTABLISHMENT_ENTRADA,
|
||||
paymentMethod: TRANSFER_PAYMENT_METHOD,
|
||||
note: `Transferência de ${fromAccount.name}`,
|
||||
note: transferNote,
|
||||
amount: formatDecimalForDbRequired(Math.abs(data.amount)),
|
||||
purchaseDate: data.date,
|
||||
transactionType: "Transferência",
|
||||
|
||||
102
app/(dashboard)/estabelecimentos/actions.ts
Normal file
102
app/(dashboard)/estabelecimentos/actions.ts
Normal 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);
|
||||
}
|
||||
}
|
||||
66
app/(dashboard)/estabelecimentos/data.ts
Normal file
66
app/(dashboard)/estabelecimentos/data.ts
Normal 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" }),
|
||||
);
|
||||
}
|
||||
23
app/(dashboard)/estabelecimentos/layout.tsx
Normal file
23
app/(dashboard)/estabelecimentos/layout.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
19
app/(dashboard)/estabelecimentos/loading.tsx
Normal file
19
app/(dashboard)/estabelecimentos/loading.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
14
app/(dashboard)/estabelecimentos/page.tsx
Normal file
14
app/(dashboard)/estabelecimentos/page.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
cartoes,
|
||||
categorias,
|
||||
contas,
|
||||
estabelecimentos,
|
||||
lancamentos,
|
||||
pagadores,
|
||||
} from "@/db/schema";
|
||||
@@ -1639,43 +1640,64 @@ export async function deleteMultipleLancamentosAction(
|
||||
}
|
||||
}
|
||||
|
||||
// Get unique establishment names from the last 3 months
|
||||
// Get unique establishment names: from estabelecimentos table + last 3 months from lancamentos
|
||||
export async function getRecentEstablishmentsAction(): Promise<string[]> {
|
||||
try {
|
||||
const user = await getUser();
|
||||
|
||||
// Calculate date 3 months ago
|
||||
const threeMonthsAgo = new Date();
|
||||
threeMonthsAgo.setMonth(threeMonthsAgo.getMonth() - 3);
|
||||
|
||||
// Fetch establishment names from the last 3 months
|
||||
const results = await db
|
||||
.select({ name: lancamentos.name })
|
||||
.from(lancamentos)
|
||||
.where(
|
||||
and(
|
||||
eq(lancamentos.userId, user.id),
|
||||
gte(lancamentos.purchaseDate, threeMonthsAgo),
|
||||
),
|
||||
)
|
||||
.orderBy(desc(lancamentos.purchaseDate));
|
||||
|
||||
// Remove duplicates and filter empty names
|
||||
const uniqueNames = Array.from(
|
||||
new Set(
|
||||
results
|
||||
.map((r) => r.name)
|
||||
.filter(
|
||||
(name): name is string =>
|
||||
name != null &&
|
||||
name.trim().length > 0 &&
|
||||
!name.toLowerCase().startsWith("pagamento fatura"),
|
||||
const [estabelecimentosRows, lancamentosResults] = await Promise.all([
|
||||
db.query.estabelecimentos.findMany({
|
||||
columns: { name: true },
|
||||
where: eq(estabelecimentos.userId, user.id),
|
||||
}),
|
||||
db
|
||||
.select({ name: lancamentos.name })
|
||||
.from(lancamentos)
|
||||
.where(
|
||||
and(
|
||||
eq(lancamentos.userId, user.id),
|
||||
gte(lancamentos.purchaseDate, threeMonthsAgo),
|
||||
),
|
||||
),
|
||||
);
|
||||
)
|
||||
.orderBy(desc(lancamentos.purchaseDate)),
|
||||
]);
|
||||
|
||||
// Return top 50 most recent unique establishments
|
||||
return uniqueNames.slice(0, 100);
|
||||
const fromTable = estabelecimentosRows
|
||||
.map((r) => r.name)
|
||||
.filter(
|
||||
(name): name is string =>
|
||||
name != null && name.trim().length > 0,
|
||||
);
|
||||
const fromLancamentos = lancamentosResults
|
||||
.map((r) => r.name)
|
||||
.filter(
|
||||
(name): name is string =>
|
||||
name != null &&
|
||||
name.trim().length > 0 &&
|
||||
!name.toLowerCase().startsWith("pagamento fatura"),
|
||||
);
|
||||
|
||||
const seen = new Set<string>();
|
||||
const unique: string[] = [];
|
||||
for (const name of fromTable) {
|
||||
const key = name.trim();
|
||||
if (!seen.has(key)) {
|
||||
seen.add(key);
|
||||
unique.push(key);
|
||||
}
|
||||
}
|
||||
for (const name of fromLancamentos) {
|
||||
const key = name.trim();
|
||||
if (!seen.has(key)) {
|
||||
seen.add(key);
|
||||
unique.push(key);
|
||||
}
|
||||
}
|
||||
|
||||
return unique.slice(0, 100);
|
||||
} catch (error) {
|
||||
console.error("Error fetching recent establishments:", error);
|
||||
return [];
|
||||
|
||||
Reference in New Issue
Block a user