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
14
CHANGELOG.md
14
CHANGELOG.md
@@ -5,6 +5,20 @@ Todas as mudanças notáveis deste projeto serão documentadas neste arquivo.
|
|||||||
O formato é baseado em [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/),
|
O formato é baseado em [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/),
|
||||||
e este projeto adere ao [Versionamento Semântico](https://semver.org/lang/pt-BR/).
|
e este projeto adere ao [Versionamento Semântico](https://semver.org/lang/pt-BR/).
|
||||||
|
|
||||||
|
## [1.6.1] - 2026-02-18
|
||||||
|
|
||||||
|
### Adicionado
|
||||||
|
|
||||||
|
- Aba "Estabelecimentos" no menu lateral (Gestão Financeira): listagem de estabelecimentos com quantidade de lançamentos, criação de novos, exclusão (apenas quando não há lançamentos vinculados) e link "Ver vinculados" para lançamentos filtrados pelo estabelecimento
|
||||||
|
- Tabela `estabelecimentos` (migration 0019) e sugestões de estabelecimento nos lançamentos passam a incluir nomes cadastrados nessa tabela
|
||||||
|
- Filtro "Estabelecimento" no drawer de Filtros da página de lançamentos; parâmetro `estabelecimento` na URL para filtrar por nome
|
||||||
|
|
||||||
|
### Alterado
|
||||||
|
|
||||||
|
- Transferências entre contas: nome do estabelecimento passa a ser "Saída - Transf. entre contas" na saída e "Entrada - Transf. entre contas" na entrada e adicionando em anotação no formato "de {conta origem} -> {conta destino}"
|
||||||
|
- Gráfico de pizza (Gastos por categoria): cores das fatias alinhadas às cores dos ícones das categorias na lista (paleta `getCategoryColor`)
|
||||||
|
- ChartContainer (Recharts): renderização do gráfico apenas após montagem no cliente e uso de `minWidth`/`minHeight` no ResponsiveContainer para evitar aviso "width(-1) and height(-1)" no console
|
||||||
|
|
||||||
## [1.6.0] - 2026-02-18
|
## [1.6.0] - 2026-02-18
|
||||||
|
|
||||||
### Adicionado
|
### Adicionado
|
||||||
|
|||||||
@@ -22,7 +22,8 @@ import { noteSchema, uuidSchema } from "@/lib/schemas/common";
|
|||||||
import {
|
import {
|
||||||
TRANSFER_CATEGORY_NAME,
|
TRANSFER_CATEGORY_NAME,
|
||||||
TRANSFER_CONDITION,
|
TRANSFER_CONDITION,
|
||||||
TRANSFER_ESTABLISHMENT,
|
TRANSFER_ESTABLISHMENT_ENTRADA,
|
||||||
|
TRANSFER_ESTABLISHMENT_SAIDA,
|
||||||
TRANSFER_PAYMENT_METHOD,
|
TRANSFER_PAYMENT_METHOD,
|
||||||
} from "@/lib/transferencias/constants";
|
} from "@/lib/transferencias/constants";
|
||||||
import { formatDecimalForDbRequired } from "@/lib/utils/currency";
|
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)
|
// Create outgoing transaction (transfer from source account)
|
||||||
await tx.insert(lancamentos).values({
|
await tx.insert(lancamentos).values({
|
||||||
condition: TRANSFER_CONDITION,
|
condition: TRANSFER_CONDITION,
|
||||||
name: `${TRANSFER_ESTABLISHMENT} → ${toAccount.name}`,
|
name: TRANSFER_ESTABLISHMENT_SAIDA,
|
||||||
paymentMethod: TRANSFER_PAYMENT_METHOD,
|
paymentMethod: TRANSFER_PAYMENT_METHOD,
|
||||||
note: `Transferência para ${toAccount.name}`,
|
note: transferNote,
|
||||||
amount: formatDecimalForDbRequired(-Math.abs(data.amount)),
|
amount: formatDecimalForDbRequired(-Math.abs(data.amount)),
|
||||||
purchaseDate: data.date,
|
purchaseDate: data.date,
|
||||||
transactionType: "Transferência",
|
transactionType: "Transferência",
|
||||||
@@ -362,9 +365,9 @@ export async function transferBetweenAccountsAction(
|
|||||||
// Create incoming transaction (transfer to destination account)
|
// Create incoming transaction (transfer to destination account)
|
||||||
await tx.insert(lancamentos).values({
|
await tx.insert(lancamentos).values({
|
||||||
condition: TRANSFER_CONDITION,
|
condition: TRANSFER_CONDITION,
|
||||||
name: `${TRANSFER_ESTABLISHMENT} ← ${fromAccount.name}`,
|
name: TRANSFER_ESTABLISHMENT_ENTRADA,
|
||||||
paymentMethod: TRANSFER_PAYMENT_METHOD,
|
paymentMethod: TRANSFER_PAYMENT_METHOD,
|
||||||
note: `Transferência de ${fromAccount.name}`,
|
note: transferNote,
|
||||||
amount: formatDecimalForDbRequired(Math.abs(data.amount)),
|
amount: formatDecimalForDbRequired(Math.abs(data.amount)),
|
||||||
purchaseDate: data.date,
|
purchaseDate: data.date,
|
||||||
transactionType: "Transferência",
|
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,
|
cartoes,
|
||||||
categorias,
|
categorias,
|
||||||
contas,
|
contas,
|
||||||
|
estabelecimentos,
|
||||||
lancamentos,
|
lancamentos,
|
||||||
pagadores,
|
pagadores,
|
||||||
} from "@/db/schema";
|
} 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[]> {
|
export async function getRecentEstablishmentsAction(): Promise<string[]> {
|
||||||
try {
|
try {
|
||||||
const user = await getUser();
|
const user = await getUser();
|
||||||
|
|
||||||
// Calculate date 3 months ago
|
|
||||||
const threeMonthsAgo = new Date();
|
const threeMonthsAgo = new Date();
|
||||||
threeMonthsAgo.setMonth(threeMonthsAgo.getMonth() - 3);
|
threeMonthsAgo.setMonth(threeMonthsAgo.getMonth() - 3);
|
||||||
|
|
||||||
// Fetch establishment names from the last 3 months
|
const [estabelecimentosRows, lancamentosResults] = await Promise.all([
|
||||||
const results = await db
|
db.query.estabelecimentos.findMany({
|
||||||
.select({ name: lancamentos.name })
|
columns: { name: true },
|
||||||
.from(lancamentos)
|
where: eq(estabelecimentos.userId, user.id),
|
||||||
.where(
|
}),
|
||||||
and(
|
db
|
||||||
eq(lancamentos.userId, user.id),
|
.select({ name: lancamentos.name })
|
||||||
gte(lancamentos.purchaseDate, threeMonthsAgo),
|
.from(lancamentos)
|
||||||
),
|
.where(
|
||||||
)
|
and(
|
||||||
.orderBy(desc(lancamentos.purchaseDate));
|
eq(lancamentos.userId, user.id),
|
||||||
|
gte(lancamentos.purchaseDate, threeMonthsAgo),
|
||||||
// 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"),
|
|
||||||
),
|
),
|
||||||
),
|
)
|
||||||
);
|
.orderBy(desc(lancamentos.purchaseDate)),
|
||||||
|
]);
|
||||||
|
|
||||||
// Return top 50 most recent unique establishments
|
const fromTable = estabelecimentosRows
|
||||||
return uniqueNames.slice(0, 100);
|
.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) {
|
} catch (error) {
|
||||||
console.error("Error fetching recent establishments:", error);
|
console.error("Error fetching recent establishments:", error);
|
||||||
return [];
|
return [];
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import { useIsMobile } from "@/hooks/use-mobile";
|
|||||||
import MoneyValues from "@/components/money-values";
|
import MoneyValues from "@/components/money-values";
|
||||||
import { type ChartConfig, ChartContainer } from "@/components/ui/chart";
|
import { type ChartConfig, ChartContainer } from "@/components/ui/chart";
|
||||||
import type { ExpensesByCategoryData } from "@/lib/dashboard/categories/expenses-by-category";
|
import type { ExpensesByCategoryData } from "@/lib/dashboard/categories/expenses-by-category";
|
||||||
|
import { getCategoryColor } from "@/lib/utils/category-colors";
|
||||||
import { formatPeriodForUrl } from "@/lib/utils/period";
|
import { formatPeriodForUrl } from "@/lib/utils/period";
|
||||||
import { WidgetEmptyState } from "../widget-empty-state";
|
import { WidgetEmptyState } from "../widget-empty-state";
|
||||||
|
|
||||||
@@ -51,24 +52,15 @@ export function ExpensesByCategoryWidgetWithChart({
|
|||||||
const isMobile = useIsMobile();
|
const isMobile = useIsMobile();
|
||||||
const periodParam = formatPeriodForUrl(period);
|
const periodParam = formatPeriodForUrl(period);
|
||||||
|
|
||||||
// Configuração do chart com cores do CSS
|
// Configuração do chart com as mesmas cores dos ícones das categorias (getCategoryColor)
|
||||||
const chartConfig = useMemo(() => {
|
const chartConfig = useMemo(() => {
|
||||||
const config: ChartConfig = {};
|
const config: ChartConfig = {};
|
||||||
const colors = [
|
|
||||||
"var(--chart-1)",
|
|
||||||
"var(--chart-2)",
|
|
||||||
"var(--chart-3)",
|
|
||||||
"var(--chart-4)",
|
|
||||||
"var(--chart-5)",
|
|
||||||
"var(--chart-1)",
|
|
||||||
"var(--chart-2)",
|
|
||||||
];
|
|
||||||
|
|
||||||
if (data.categories.length <= 7) {
|
if (data.categories.length <= 7) {
|
||||||
data.categories.forEach((category, index) => {
|
data.categories.forEach((category, index) => {
|
||||||
config[category.categoryId] = {
|
config[category.categoryId] = {
|
||||||
label: category.categoryName,
|
label: category.categoryName,
|
||||||
color: colors[index % colors.length],
|
color: getCategoryColor(index),
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
@@ -77,12 +69,12 @@ export function ExpensesByCategoryWidgetWithChart({
|
|||||||
top7.forEach((category, index) => {
|
top7.forEach((category, index) => {
|
||||||
config[category.categoryId] = {
|
config[category.categoryId] = {
|
||||||
label: category.categoryName,
|
label: category.categoryName,
|
||||||
color: colors[index % colors.length],
|
color: getCategoryColor(index),
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
config.outros = {
|
config.outros = {
|
||||||
label: "Outros",
|
label: "Outros",
|
||||||
color: "var(--chart-6)",
|
color: getCategoryColor(7),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,97 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState, useTransition } from "react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { createEstabelecimentoAction } from "@/app/(dashboard)/estabelecimentos/actions";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
DialogTrigger,
|
||||||
|
} from "@/components/ui/dialog";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Label } from "@/components/ui/label";
|
||||||
|
import { RiAddCircleLine } from "@remixicon/react";
|
||||||
|
|
||||||
|
interface EstabelecimentoCreateDialogProps {
|
||||||
|
trigger?: React.ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function EstabelecimentoCreateDialog({
|
||||||
|
trigger,
|
||||||
|
}: EstabelecimentoCreateDialogProps) {
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const [name, setName] = useState("");
|
||||||
|
const [isPending, startTransition] = useTransition();
|
||||||
|
|
||||||
|
const handleSubmit = (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const trimmed = name.trim();
|
||||||
|
if (!trimmed) return;
|
||||||
|
|
||||||
|
startTransition(async () => {
|
||||||
|
const result = await createEstabelecimentoAction({ name: trimmed });
|
||||||
|
if (result.success) {
|
||||||
|
toast.success(result.message);
|
||||||
|
setName("");
|
||||||
|
setOpen(false);
|
||||||
|
} else {
|
||||||
|
toast.error(result.error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={setOpen}>
|
||||||
|
<DialogTrigger asChild>
|
||||||
|
{trigger ?? (
|
||||||
|
<Button>
|
||||||
|
<RiAddCircleLine className="size-4" />
|
||||||
|
Novo estabelecimento
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</DialogTrigger>
|
||||||
|
<DialogContent>
|
||||||
|
<form onSubmit={handleSubmit}>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Novo estabelecimento</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
Adicione um nome para usar nos lançamentos. Ele aparecerá na lista
|
||||||
|
e nas sugestões ao criar ou editar lançamentos.
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<div className="grid gap-4 py-4">
|
||||||
|
<div className="grid gap-2">
|
||||||
|
<Label htmlFor="estabelecimento-name">Nome</Label>
|
||||||
|
<Input
|
||||||
|
id="estabelecimento-name"
|
||||||
|
value={name}
|
||||||
|
onChange={(e) => setName(e.target.value)}
|
||||||
|
placeholder="Ex: Supermercado, Posto, Farmácia"
|
||||||
|
disabled={isPending}
|
||||||
|
autoFocus
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<DialogFooter>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => setOpen(false)}
|
||||||
|
disabled={isPending}
|
||||||
|
>
|
||||||
|
Cancelar
|
||||||
|
</Button>
|
||||||
|
<Button type="submit" disabled={isPending || !name.trim()}>
|
||||||
|
{isPending ? "Salvando…" : "Criar"}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</form>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
154
components/estabelecimentos/estabelecimentos-page.tsx
Normal file
154
components/estabelecimentos/estabelecimentos-page.tsx
Normal file
@@ -0,0 +1,154 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { RiDeleteBin5Line, RiExternalLinkLine } from "@remixicon/react";
|
||||||
|
import Link from "next/link";
|
||||||
|
import { useCallback, useState } from "react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { deleteEstabelecimentoAction } from "@/app/(dashboard)/estabelecimentos/actions";
|
||||||
|
import { ConfirmActionDialog } from "@/components/confirm-action-dialog";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import {
|
||||||
|
Table,
|
||||||
|
TableBody,
|
||||||
|
TableCell,
|
||||||
|
TableHead,
|
||||||
|
TableHeader,
|
||||||
|
TableRow,
|
||||||
|
} from "@/components/ui/table";
|
||||||
|
import { EstabelecimentoLogo } from "@/components/lancamentos/shared/estabelecimento-logo";
|
||||||
|
import { EstabelecimentoCreateDialog } from "./estabelecimento-create-dialog";
|
||||||
|
import type { EstabelecimentoRow } from "@/app/(dashboard)/estabelecimentos/data";
|
||||||
|
|
||||||
|
interface EstabelecimentosPageProps {
|
||||||
|
rows: EstabelecimentoRow[];
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildLancamentosUrl(name: string): string {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
params.set("estabelecimento", name);
|
||||||
|
return `/lancamentos?${params.toString()}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function EstabelecimentosPage({ rows }: EstabelecimentosPageProps) {
|
||||||
|
const [deleteOpen, setDeleteOpen] = useState(false);
|
||||||
|
const [rowToDelete, setRowToDelete] = useState<EstabelecimentoRow | null>(
|
||||||
|
null,
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleDeleteRequest = useCallback((row: EstabelecimentoRow) => {
|
||||||
|
setRowToDelete(row);
|
||||||
|
setDeleteOpen(true);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleDeleteOpenChange = useCallback((open: boolean) => {
|
||||||
|
setDeleteOpen(open);
|
||||||
|
if (!open) setRowToDelete(null);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleDeleteConfirm = useCallback(async () => {
|
||||||
|
if (!rowToDelete?.estabelecimentoId) return;
|
||||||
|
|
||||||
|
const result = await deleteEstabelecimentoAction({
|
||||||
|
id: rowToDelete.estabelecimentoId,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (result.success) {
|
||||||
|
toast.success(result.message);
|
||||||
|
setDeleteOpen(false);
|
||||||
|
setRowToDelete(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
toast.error(result.error);
|
||||||
|
throw new Error(result.error);
|
||||||
|
}, [rowToDelete]);
|
||||||
|
|
||||||
|
const canDelete = (row: EstabelecimentoRow) =>
|
||||||
|
row.lancamentosCount === 0 && row.estabelecimentoId != null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div className="flex w-full flex-col gap-6">
|
||||||
|
<div className="flex justify-start">
|
||||||
|
<EstabelecimentoCreateDialog />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{rows.length === 0 ? (
|
||||||
|
<div className="flex min-h-[280px] items-center justify-center rounded-lg border border-dashed bg-muted/10 p-10 text-center text-sm text-muted-foreground">
|
||||||
|
Nenhum estabelecimento ainda. Crie um ou use a lista que será
|
||||||
|
preenchida conforme você adiciona lançamentos.
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="rounded-md border">
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow>
|
||||||
|
<TableHead>Estabelecimento</TableHead>
|
||||||
|
<TableHead className="text-right">Lançamentos</TableHead>
|
||||||
|
<TableHead className="w-[180px] text-right">Ações</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{rows.map((row) => (
|
||||||
|
<TableRow key={`${row.name}-${row.estabelecimentoId ?? "x"}`}>
|
||||||
|
<TableCell>
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<EstabelecimentoLogo name={row.name} size={32} />
|
||||||
|
<span className="font-medium">{row.name}</span>
|
||||||
|
</div>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-right">
|
||||||
|
{row.lancamentosCount}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-right">
|
||||||
|
<div className="flex justify-end gap-2">
|
||||||
|
<Button variant="ghost" size="sm" asChild>
|
||||||
|
<Link
|
||||||
|
href={buildLancamentosUrl(row.name)}
|
||||||
|
className="inline-flex items-center gap-1"
|
||||||
|
>
|
||||||
|
<RiExternalLinkLine className="size-4" />
|
||||||
|
Ver vinculados
|
||||||
|
</Link>
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="text-destructive hover:text-destructive"
|
||||||
|
disabled={!canDelete(row)}
|
||||||
|
onClick={() => handleDeleteRequest(row)}
|
||||||
|
title={
|
||||||
|
row.lancamentosCount > 0
|
||||||
|
? "Não é possível excluir: há lançamentos vinculados."
|
||||||
|
: "Excluir estabelecimento"
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<RiDeleteBin5Line className="size-4" />
|
||||||
|
Excluir
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ConfirmActionDialog
|
||||||
|
open={deleteOpen}
|
||||||
|
onOpenChange={handleDeleteOpenChange}
|
||||||
|
title="Excluir estabelecimento?"
|
||||||
|
description={
|
||||||
|
rowToDelete
|
||||||
|
? `Tem certeza que deseja excluir "${rowToDelete.name}"? Esta ação não pode ser desfeita.`
|
||||||
|
: ""
|
||||||
|
}
|
||||||
|
confirmLabel="Excluir"
|
||||||
|
variant="destructive"
|
||||||
|
onConfirm={handleDeleteConfirm}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -386,6 +386,7 @@ export function LancamentosPage({
|
|||||||
pagadorFilterOptions={pagadorFilterOptions}
|
pagadorFilterOptions={pagadorFilterOptions}
|
||||||
categoriaFilterOptions={categoriaFilterOptions}
|
categoriaFilterOptions={categoriaFilterOptions}
|
||||||
contaCartaoFilterOptions={contaCartaoFilterOptions}
|
contaCartaoFilterOptions={contaCartaoFilterOptions}
|
||||||
|
estabelecimentosOptions={estabelecimentos}
|
||||||
selectedPeriod={selectedPeriod}
|
selectedPeriod={selectedPeriod}
|
||||||
onCreate={allowCreate ? handleCreate : undefined}
|
onCreate={allowCreate ? handleCreate : undefined}
|
||||||
onMassAdd={allowCreate ? handleMassAdd : undefined}
|
onMassAdd={allowCreate ? handleMassAdd : undefined}
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ export function EstabelecimentoInput({
|
|||||||
value,
|
value,
|
||||||
onChange,
|
onChange,
|
||||||
estabelecimentos = [],
|
estabelecimentos = [],
|
||||||
placeholder = "Ex.: Padaria",
|
placeholder = "Ex.: Padaria, Transferência, Saldo inicial",
|
||||||
required = false,
|
required = false,
|
||||||
maxLength = 20,
|
maxLength = 20,
|
||||||
}: EstabelecimentoInputProps) {
|
}: EstabelecimentoInputProps) {
|
||||||
|
|||||||
@@ -122,6 +122,7 @@ interface LancamentosFiltersProps {
|
|||||||
pagadorOptions: LancamentoFilterOption[];
|
pagadorOptions: LancamentoFilterOption[];
|
||||||
categoriaOptions: LancamentoFilterOption[];
|
categoriaOptions: LancamentoFilterOption[];
|
||||||
contaCartaoOptions: ContaCartaoFilterOption[];
|
contaCartaoOptions: ContaCartaoFilterOption[];
|
||||||
|
estabelecimentosOptions?: string[];
|
||||||
className?: string;
|
className?: string;
|
||||||
exportButton?: ReactNode;
|
exportButton?: ReactNode;
|
||||||
hideAdvancedFilters?: boolean;
|
hideAdvancedFilters?: boolean;
|
||||||
@@ -131,6 +132,7 @@ export function LancamentosFilters({
|
|||||||
pagadorOptions,
|
pagadorOptions,
|
||||||
categoriaOptions,
|
categoriaOptions,
|
||||||
contaCartaoOptions,
|
contaCartaoOptions,
|
||||||
|
estabelecimentosOptions = [],
|
||||||
className,
|
className,
|
||||||
exportButton,
|
exportButton,
|
||||||
hideAdvancedFilters = false,
|
hideAdvancedFilters = false,
|
||||||
@@ -235,6 +237,16 @@ export function LancamentosFilters({
|
|||||||
? contaCartaoOptions.find((option) => option.slug === contaCartaoValue)
|
? contaCartaoOptions.find((option) => option.slug === contaCartaoValue)
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
|
const estabelecimentoParam = searchParams.get("estabelecimento");
|
||||||
|
const estabelecimentoOptionsForSelect = [
|
||||||
|
...(estabelecimentoParam &&
|
||||||
|
estabelecimentoParam.trim() &&
|
||||||
|
!estabelecimentosOptions.includes(estabelecimentoParam.trim())
|
||||||
|
? [estabelecimentoParam.trim()]
|
||||||
|
: []),
|
||||||
|
...estabelecimentosOptions,
|
||||||
|
];
|
||||||
|
|
||||||
const [categoriaOpen, setCategoriaOpen] = useState(false);
|
const [categoriaOpen, setCategoriaOpen] = useState(false);
|
||||||
const [drawerOpen, setDrawerOpen] = useState(false);
|
const [drawerOpen, setDrawerOpen] = useState(false);
|
||||||
|
|
||||||
@@ -244,7 +256,8 @@ export function LancamentosFilters({
|
|||||||
searchParams.get("pagamento") ||
|
searchParams.get("pagamento") ||
|
||||||
searchParams.get("pagador") ||
|
searchParams.get("pagador") ||
|
||||||
searchParams.get("categoria") ||
|
searchParams.get("categoria") ||
|
||||||
searchParams.get("contaCartao");
|
searchParams.get("contaCartao") ||
|
||||||
|
searchParams.get("estabelecimento");
|
||||||
|
|
||||||
const handleResetFilters = () => {
|
const handleResetFilters = () => {
|
||||||
handleReset();
|
handleReset();
|
||||||
@@ -518,6 +531,45 @@ export function LancamentosFilters({
|
|||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{estabelecimentoOptionsForSelect.length > 0 ||
|
||||||
|
estabelecimentoParam?.trim() ? (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label className="text-sm font-medium">Estabelecimento</label>
|
||||||
|
<Select
|
||||||
|
value={
|
||||||
|
getParamValue("estabelecimento") || FILTER_EMPTY_VALUE
|
||||||
|
}
|
||||||
|
onValueChange={(value) =>
|
||||||
|
handleFilterChange(
|
||||||
|
"estabelecimento",
|
||||||
|
value === FILTER_EMPTY_VALUE ? null : value,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
disabled={isPending}
|
||||||
|
>
|
||||||
|
<SelectTrigger
|
||||||
|
className="w-full text-sm border-dashed"
|
||||||
|
disabled={isPending}
|
||||||
|
>
|
||||||
|
<span className="truncate">
|
||||||
|
{getParamValue("estabelecimento") !== FILTER_EMPTY_VALUE &&
|
||||||
|
searchParams.get("estabelecimento")
|
||||||
|
? searchParams.get("estabelecimento")
|
||||||
|
: "Todos"}
|
||||||
|
</span>
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value={FILTER_EMPTY_VALUE}>Todos</SelectItem>
|
||||||
|
{estabelecimentoOptionsForSelect.map((name) => (
|
||||||
|
<SelectItem key={name} value={name}>
|
||||||
|
{name}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<DrawerFooter>
|
<DrawerFooter>
|
||||||
|
|||||||
@@ -715,6 +715,7 @@ type LancamentosTableProps = {
|
|||||||
pagadorFilterOptions?: LancamentoFilterOption[];
|
pagadorFilterOptions?: LancamentoFilterOption[];
|
||||||
categoriaFilterOptions?: LancamentoFilterOption[];
|
categoriaFilterOptions?: LancamentoFilterOption[];
|
||||||
contaCartaoFilterOptions?: ContaCartaoFilterOption[];
|
contaCartaoFilterOptions?: ContaCartaoFilterOption[];
|
||||||
|
estabelecimentosOptions?: string[];
|
||||||
selectedPeriod?: string;
|
selectedPeriod?: string;
|
||||||
onCreate?: (type: "Despesa" | "Receita") => void;
|
onCreate?: (type: "Despesa" | "Receita") => void;
|
||||||
onMassAdd?: () => void;
|
onMassAdd?: () => void;
|
||||||
@@ -741,6 +742,7 @@ export function LancamentosTable({
|
|||||||
pagadorFilterOptions = [],
|
pagadorFilterOptions = [],
|
||||||
categoriaFilterOptions = [],
|
categoriaFilterOptions = [],
|
||||||
contaCartaoFilterOptions = [],
|
contaCartaoFilterOptions = [],
|
||||||
|
estabelecimentosOptions = [],
|
||||||
selectedPeriod,
|
selectedPeriod,
|
||||||
onCreate,
|
onCreate,
|
||||||
onMassAdd,
|
onMassAdd,
|
||||||
@@ -921,6 +923,7 @@ export function LancamentosTable({
|
|||||||
pagadorOptions={pagadorFilterOptions}
|
pagadorOptions={pagadorFilterOptions}
|
||||||
categoriaOptions={categoriaFilterOptions}
|
categoriaOptions={categoriaFilterOptions}
|
||||||
contaCartaoOptions={contaCartaoFilterOptions}
|
contaCartaoOptions={contaCartaoFilterOptions}
|
||||||
|
estabelecimentosOptions={estabelecimentosOptions}
|
||||||
className="w-full lg:flex-1 lg:justify-end"
|
className="w-full lg:flex-1 lg:justify-end"
|
||||||
hideAdvancedFilters={hasOtherUserData}
|
hideAdvancedFilters={hasOtherUserData}
|
||||||
exportButton={
|
exportButton={
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import {
|
|||||||
RiPriceTag3Line,
|
RiPriceTag3Line,
|
||||||
RiSettings2Line,
|
RiSettings2Line,
|
||||||
RiSparklingLine,
|
RiSparklingLine,
|
||||||
|
RiStore2Line,
|
||||||
RiTodoLine,
|
RiTodoLine,
|
||||||
} from "@remixicon/react";
|
} from "@remixicon/react";
|
||||||
|
|
||||||
@@ -125,6 +126,11 @@ export function createSidebarNavData(
|
|||||||
url: "/orcamentos",
|
url: "/orcamentos",
|
||||||
icon: RiFundsLine,
|
icon: RiFundsLine,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
title: "Estabelecimentos",
|
||||||
|
url: "/estabelecimentos",
|
||||||
|
icon: RiStore2Line,
|
||||||
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -49,24 +49,36 @@ function ChartContainer({
|
|||||||
}) {
|
}) {
|
||||||
const uniqueId = React.useId();
|
const uniqueId = React.useId();
|
||||||
const chartId = `chart-${id || uniqueId.replace(/:/g, "")}`;
|
const chartId = `chart-${id || uniqueId.replace(/:/g, "")}`;
|
||||||
|
const [mounted, setMounted] = React.useState(false);
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
setMounted(true);
|
||||||
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ChartContext.Provider value={{ config }}>
|
<ChartContext.Provider value={{ config }}>
|
||||||
<div
|
<div
|
||||||
data-slot="chart"
|
data-slot="chart"
|
||||||
data-chart={chartId}
|
data-chart={chartId}
|
||||||
style={{ minWidth: 0, minHeight: 0, ...style }}
|
style={style}
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex w-full min-h-0 min-w-0 justify-center text-xs aspect-video [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-hidden [&_.recharts-sector]:outline-hidden [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-surface]:outline-hidden",
|
"flex w-full min-w-0 min-h-[200px] justify-center text-xs aspect-video [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-hidden [&_.recharts-sector]:outline-hidden [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-surface]:outline-hidden",
|
||||||
className,
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
<ChartStyle id={chartId} config={config} />
|
<ChartStyle id={chartId} config={config} />
|
||||||
<div className="h-full w-full">
|
<div className="h-full w-full min-h-[200px] min-w-[280px]">
|
||||||
<RechartsPrimitive.ResponsiveContainer width="100%" height="100%">
|
{mounted ? (
|
||||||
{children}
|
<RechartsPrimitive.ResponsiveContainer
|
||||||
</RechartsPrimitive.ResponsiveContainer>
|
width="100%"
|
||||||
|
height="100%"
|
||||||
|
minWidth={280}
|
||||||
|
minHeight={200}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</RechartsPrimitive.ResponsiveContainer>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</ChartContext.Provider>
|
</ChartContext.Provider>
|
||||||
|
|||||||
35
db/schema.ts
35
db/schema.ts
@@ -190,6 +190,30 @@ export const categorias = pgTable(
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
export const estabelecimentos = pgTable(
|
||||||
|
"estabelecimentos",
|
||||||
|
{
|
||||||
|
id: uuid("id").primaryKey().default(sql`gen_random_uuid()`),
|
||||||
|
name: text("nome").notNull(),
|
||||||
|
userId: text("user_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => user.id, { onDelete: "cascade" }),
|
||||||
|
createdAt: timestamp("created_at", {
|
||||||
|
mode: "date",
|
||||||
|
withTimezone: true,
|
||||||
|
})
|
||||||
|
.notNull()
|
||||||
|
.defaultNow(),
|
||||||
|
},
|
||||||
|
(table) => ({
|
||||||
|
userIdIdx: index("estabelecimentos_user_id_idx").on(table.userId),
|
||||||
|
userIdNameUnique: uniqueIndex("estabelecimentos_user_id_nome_key").on(
|
||||||
|
table.userId,
|
||||||
|
table.name,
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
export const pagadores = pgTable(
|
export const pagadores = pgTable(
|
||||||
"pagadores",
|
"pagadores",
|
||||||
{
|
{
|
||||||
@@ -635,6 +659,7 @@ export const userRelations = relations(user, ({ many, one }) => ({
|
|||||||
cartoes: many(cartoes),
|
cartoes: many(cartoes),
|
||||||
categorias: many(categorias),
|
categorias: many(categorias),
|
||||||
contas: many(contas),
|
contas: many(contas),
|
||||||
|
estabelecimentos: many(estabelecimentos),
|
||||||
faturas: many(faturas),
|
faturas: many(faturas),
|
||||||
lancamentos: many(lancamentos),
|
lancamentos: many(lancamentos),
|
||||||
orcamentos: many(orcamentos),
|
orcamentos: many(orcamentos),
|
||||||
@@ -676,6 +701,16 @@ export const categoriasRelations = relations(categorias, ({ one, many }) => ({
|
|||||||
orcamentos: many(orcamentos),
|
orcamentos: many(orcamentos),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
export const estabelecimentosRelations = relations(
|
||||||
|
estabelecimentos,
|
||||||
|
({ one }) => ({
|
||||||
|
user: one(user, {
|
||||||
|
fields: [estabelecimentos.userId],
|
||||||
|
references: [user.id],
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
export const pagadoresRelations = relations(pagadores, ({ one, many }) => ({
|
export const pagadoresRelations = relations(pagadores, ({ one, many }) => ({
|
||||||
user: one(user, {
|
user: one(user, {
|
||||||
fields: [pagadores.userId],
|
fields: [pagadores.userId],
|
||||||
|
|||||||
16
drizzle/0019_add_estabelecimentos.sql
Normal file
16
drizzle/0019_add_estabelecimentos.sql
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
CREATE TABLE IF NOT EXISTS "estabelecimentos" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"nome" text NOT NULL,
|
||||||
|
"user_id" text NOT NULL,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS "estabelecimentos_user_id_idx" ON "estabelecimentos" ("user_id");
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS "estabelecimentos_user_id_nome_key" ON "estabelecimentos" ("user_id", "nome");
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
ALTER TABLE "estabelecimentos" ADD CONSTRAINT "estabelecimentos_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;
|
||||||
|
EXCEPTION
|
||||||
|
WHEN duplicate_object THEN null;
|
||||||
|
END $$;
|
||||||
@@ -25,6 +25,7 @@ export const revalidateConfig = {
|
|||||||
cartoes: ["/cartoes", "/contas", "/lancamentos"],
|
cartoes: ["/cartoes", "/contas", "/lancamentos"],
|
||||||
contas: ["/contas", "/lancamentos"],
|
contas: ["/contas", "/lancamentos"],
|
||||||
categorias: ["/categorias"],
|
categorias: ["/categorias"],
|
||||||
|
estabelecimentos: ["/estabelecimentos", "/lancamentos"],
|
||||||
orcamentos: ["/orcamentos"],
|
orcamentos: ["/orcamentos"],
|
||||||
pagadores: ["/pagadores"],
|
pagadores: ["/pagadores"],
|
||||||
anotacoes: ["/anotacoes", "/anotacoes/arquivadas"],
|
anotacoes: ["/anotacoes", "/anotacoes/arquivadas"],
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ export type LancamentoSearchFilters = {
|
|||||||
categoriaFilter: string | null;
|
categoriaFilter: string | null;
|
||||||
contaCartaoFilter: string | null;
|
contaCartaoFilter: string | null;
|
||||||
searchFilter: string | null;
|
searchFilter: string | null;
|
||||||
|
estabelecimentoFilter: string | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
type BaseSluggedOption = {
|
type BaseSluggedOption = {
|
||||||
@@ -122,6 +123,7 @@ export const extractLancamentoSearchFilters = (
|
|||||||
categoriaFilter: getSingleParam(params, "categoria"),
|
categoriaFilter: getSingleParam(params, "categoria"),
|
||||||
contaCartaoFilter: getSingleParam(params, "contaCartao"),
|
contaCartaoFilter: getSingleParam(params, "contaCartao"),
|
||||||
searchFilter: getSingleParam(params, "q"),
|
searchFilter: getSingleParam(params, "q"),
|
||||||
|
estabelecimentoFilter: getSingleParam(params, "estabelecimento"),
|
||||||
});
|
});
|
||||||
|
|
||||||
const normalizeLabel = (value: string | null | undefined) =>
|
const normalizeLabel = (value: string | null | undefined) =>
|
||||||
@@ -368,6 +370,10 @@ export const buildLancamentoWhere = ({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (filters.estabelecimentoFilter?.trim()) {
|
||||||
|
where.push(eq(lancamentos.name, filters.estabelecimentoFilter.trim()));
|
||||||
|
}
|
||||||
|
|
||||||
const searchPattern = buildSearchPattern(filters.searchFilter);
|
const searchPattern = buildSearchPattern(filters.searchFilter);
|
||||||
if (searchPattern) {
|
if (searchPattern) {
|
||||||
where.push(
|
where.push(
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
export const TRANSFER_CATEGORY_NAME = "Transferência interna";
|
export const TRANSFER_CATEGORY_NAME = "Transferência interna";
|
||||||
export const TRANSFER_ESTABLISHMENT = "Transf. entre contas";
|
export const TRANSFER_ESTABLISHMENT = "Transf. entre contas";
|
||||||
|
export const TRANSFER_ESTABLISHMENT_SAIDA = "Saída - Transf. entre contas";
|
||||||
|
export const TRANSFER_ESTABLISHMENT_ENTRADA = "Entrada - Transf. entre contas";
|
||||||
export const TRANSFER_PAGADOR = "Admin";
|
export const TRANSFER_PAGADOR = "Admin";
|
||||||
export const TRANSFER_PAYMENT_METHOD = "Pix";
|
export const TRANSFER_PAYMENT_METHOD = "Pix";
|
||||||
export const TRANSFER_CONDITION = "À vista";
|
export const TRANSFER_CONDITION = "À vista";
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "openmonetis",
|
"name": "openmonetis",
|
||||||
"version": "1.6.0",
|
"version": "1.6.1",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "next dev --turbopack",
|
"dev": "next dev --turbopack",
|
||||||
|
|||||||
Reference in New Issue
Block a user