mirror of
https://github.com/felipegcoutinho/openmonetis.git
synced 2026-05-09 11:01:45 +00:00
refactor: alinha features financeiras ao novo naming
This commit is contained in:
@@ -2,7 +2,7 @@
|
||||
|
||||
import { and, eq, ne } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { categorias, orcamentos } from "@/db/schema";
|
||||
import { budgets, categories } from "@/db/schema";
|
||||
import {
|
||||
handleActionError,
|
||||
revalidateForEntity,
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
import { getPreviousPeriod } from "@/shared/utils/period";
|
||||
|
||||
const budgetBaseSchema = z.object({
|
||||
categoriaId: uuidSchema("Categoria"),
|
||||
categoryId: uuidSchema("Category"),
|
||||
period: periodSchema,
|
||||
amount: z
|
||||
.string({ message: "Informe o valor limite." })
|
||||
@@ -48,21 +48,21 @@ type BudgetCreateInput = z.input<typeof createBudgetSchema>;
|
||||
type BudgetUpdateInput = z.input<typeof updateBudgetSchema>;
|
||||
type BudgetDeleteInput = z.input<typeof deleteBudgetSchema>;
|
||||
type BudgetCopyRow = {
|
||||
categoriaId: string | null;
|
||||
categoryId: string | null;
|
||||
amount: unknown;
|
||||
};
|
||||
|
||||
const ensureCategory = async (userId: string, categoriaId: string) => {
|
||||
const category = await db.query.categorias.findFirst({
|
||||
const ensureCategory = async (userId: string, categoryId: string) => {
|
||||
const category = await db.query.categories.findFirst({
|
||||
columns: {
|
||||
id: true,
|
||||
type: true,
|
||||
},
|
||||
where: and(eq(categorias.id, categoriaId), eq(categorias.userId, userId)),
|
||||
where: and(eq(categories.id, categoryId), eq(categories.userId, userId)),
|
||||
});
|
||||
|
||||
if (!category) {
|
||||
throw new Error("Categoria não encontrada.");
|
||||
throw new Error("Category não encontrada.");
|
||||
}
|
||||
|
||||
if (category.type !== "despesa") {
|
||||
@@ -77,15 +77,15 @@ export async function createBudgetAction(
|
||||
const user = await getUser();
|
||||
const data = createBudgetSchema.parse(input);
|
||||
|
||||
await ensureCategory(user.id, data.categoriaId);
|
||||
await ensureCategory(user.id, data.categoryId);
|
||||
|
||||
const duplicateConditions = [
|
||||
eq(orcamentos.userId, user.id),
|
||||
eq(orcamentos.period, data.period),
|
||||
eq(orcamentos.categoriaId, data.categoriaId),
|
||||
eq(budgets.userId, user.id),
|
||||
eq(budgets.period, data.period),
|
||||
eq(budgets.categoryId, data.categoryId),
|
||||
] as const;
|
||||
|
||||
const duplicate = await db.query.orcamentos.findFirst({
|
||||
const duplicate = await db.query.budgets.findFirst({
|
||||
columns: { id: true },
|
||||
where: and(...duplicateConditions),
|
||||
});
|
||||
@@ -98,14 +98,14 @@ export async function createBudgetAction(
|
||||
};
|
||||
}
|
||||
|
||||
await db.insert(orcamentos).values({
|
||||
await db.insert(budgets).values({
|
||||
amount: formatDecimalForDbRequired(data.amount),
|
||||
period: data.period,
|
||||
userId: user.id,
|
||||
categoriaId: data.categoriaId,
|
||||
categoryId: data.categoryId,
|
||||
});
|
||||
|
||||
revalidateForEntity("orcamentos");
|
||||
revalidateForEntity("budgets");
|
||||
|
||||
return { success: true, message: "Orçamento criado com sucesso." };
|
||||
} catch (error) {
|
||||
@@ -120,16 +120,16 @@ export async function updateBudgetAction(
|
||||
const user = await getUser();
|
||||
const data = updateBudgetSchema.parse(input);
|
||||
|
||||
await ensureCategory(user.id, data.categoriaId);
|
||||
await ensureCategory(user.id, data.categoryId);
|
||||
|
||||
const duplicateConditions = [
|
||||
eq(orcamentos.userId, user.id),
|
||||
eq(orcamentos.period, data.period),
|
||||
eq(orcamentos.categoriaId, data.categoriaId),
|
||||
ne(orcamentos.id, data.id),
|
||||
eq(budgets.userId, user.id),
|
||||
eq(budgets.period, data.period),
|
||||
eq(budgets.categoryId, data.categoryId),
|
||||
ne(budgets.id, data.id),
|
||||
] as const;
|
||||
|
||||
const duplicate = await db.query.orcamentos.findFirst({
|
||||
const duplicate = await db.query.budgets.findFirst({
|
||||
columns: { id: true },
|
||||
where: and(...duplicateConditions),
|
||||
});
|
||||
@@ -143,14 +143,14 @@ export async function updateBudgetAction(
|
||||
}
|
||||
|
||||
const [updated] = await db
|
||||
.update(orcamentos)
|
||||
.update(budgets)
|
||||
.set({
|
||||
amount: formatDecimalForDbRequired(data.amount),
|
||||
period: data.period,
|
||||
categoriaId: data.categoriaId,
|
||||
categoryId: data.categoryId,
|
||||
})
|
||||
.where(and(eq(orcamentos.id, data.id), eq(orcamentos.userId, user.id)))
|
||||
.returning({ id: orcamentos.id });
|
||||
.where(and(eq(budgets.id, data.id), eq(budgets.userId, user.id)))
|
||||
.returning({ id: budgets.id });
|
||||
|
||||
if (!updated) {
|
||||
return {
|
||||
@@ -159,7 +159,7 @@ export async function updateBudgetAction(
|
||||
};
|
||||
}
|
||||
|
||||
revalidateForEntity("orcamentos");
|
||||
revalidateForEntity("budgets");
|
||||
|
||||
return { success: true, message: "Orçamento atualizado com sucesso." };
|
||||
} catch (error) {
|
||||
@@ -175,9 +175,9 @@ export async function deleteBudgetAction(
|
||||
const data = deleteBudgetSchema.parse(input);
|
||||
|
||||
const [deleted] = await db
|
||||
.delete(orcamentos)
|
||||
.where(and(eq(orcamentos.id, data.id), eq(orcamentos.userId, user.id)))
|
||||
.returning({ id: orcamentos.id });
|
||||
.delete(budgets)
|
||||
.where(and(eq(budgets.id, data.id), eq(budgets.userId, user.id)))
|
||||
.returning({ id: budgets.id });
|
||||
|
||||
if (!deleted) {
|
||||
return {
|
||||
@@ -186,7 +186,7 @@ export async function deleteBudgetAction(
|
||||
};
|
||||
}
|
||||
|
||||
revalidateForEntity("orcamentos");
|
||||
revalidateForEntity("budgets");
|
||||
|
||||
return { success: true, message: "Orçamento removido com sucesso." };
|
||||
} catch (error) {
|
||||
@@ -211,10 +211,10 @@ export async function duplicatePreviousMonthBudgetsAction(
|
||||
const previousPeriod = getPreviousPeriod(data.period);
|
||||
|
||||
// Buscar orçamentos do mês anterior
|
||||
const previousBudgets = (await db.query.orcamentos.findMany({
|
||||
const previousBudgets = (await db.query.budgets.findMany({
|
||||
where: and(
|
||||
eq(orcamentos.userId, user.id),
|
||||
eq(orcamentos.period, previousPeriod),
|
||||
eq(budgets.userId, user.id),
|
||||
eq(budgets.period, previousPeriod),
|
||||
),
|
||||
})) as BudgetCopyRow[];
|
||||
|
||||
@@ -226,41 +226,38 @@ export async function duplicatePreviousMonthBudgetsAction(
|
||||
}
|
||||
|
||||
// Buscar orçamentos existentes do mês atual
|
||||
const currentBudgets = (await db.query.orcamentos.findMany({
|
||||
where: and(
|
||||
eq(orcamentos.userId, user.id),
|
||||
eq(orcamentos.period, data.period),
|
||||
),
|
||||
const currentBudgets = (await db.query.budgets.findMany({
|
||||
where: and(eq(budgets.userId, user.id), eq(budgets.period, data.period)),
|
||||
})) as BudgetCopyRow[];
|
||||
|
||||
// Filtrar para evitar duplicatas
|
||||
const existingCategoryIds = new Set(
|
||||
currentBudgets.map((b) => b.categoriaId),
|
||||
currentBudgets.map((b) => b.categoryId),
|
||||
);
|
||||
|
||||
const budgetsToCopy = previousBudgets.filter(
|
||||
(b) => b.categoriaId && !existingCategoryIds.has(b.categoriaId),
|
||||
(b) => b.categoryId && !existingCategoryIds.has(b.categoryId),
|
||||
);
|
||||
|
||||
if (budgetsToCopy.length === 0) {
|
||||
return {
|
||||
success: false,
|
||||
error:
|
||||
"Todas as categorias do mês anterior já possuem orçamento neste mês.",
|
||||
"Todas as categories do mês anterior já possuem orçamento neste mês.",
|
||||
};
|
||||
}
|
||||
|
||||
// Inserir novos orçamentos
|
||||
await db.insert(orcamentos).values(
|
||||
await db.insert(budgets).values(
|
||||
budgetsToCopy.map((b) => ({
|
||||
amount: b.amount,
|
||||
amount: b.amount as string,
|
||||
period: data.period,
|
||||
userId: user.id,
|
||||
categoriaId: b.categoriaId as string,
|
||||
categoryId: b.categoryId as string,
|
||||
})),
|
||||
);
|
||||
|
||||
revalidateForEntity("orcamentos");
|
||||
revalidateForEntity("budgets");
|
||||
|
||||
return {
|
||||
success: true,
|
||||
|
||||
@@ -30,7 +30,7 @@ const buildUsagePercent = (spent: number, limit: number) => {
|
||||
};
|
||||
|
||||
const formatCategoryName = (budget: Budget) =>
|
||||
budget.category?.name ?? "Categoria removida";
|
||||
budget.category?.name ?? "Category removida";
|
||||
|
||||
export function BudgetCard({
|
||||
budget,
|
||||
|
||||
@@ -50,7 +50,7 @@ const buildInitialValues = ({
|
||||
budget?: Budget;
|
||||
defaultPeriod: string;
|
||||
}): BudgetFormValues => ({
|
||||
categoriaId: budget?.category?.id ?? "",
|
||||
categoryId: budget?.category?.id ?? "",
|
||||
period: budget?.period ?? defaultPeriod,
|
||||
amount: budget ? (Math.round(budget.amount * 100) / 100).toFixed(2) : "",
|
||||
});
|
||||
@@ -113,7 +113,7 @@ export function BudgetDialog({
|
||||
return;
|
||||
}
|
||||
|
||||
if (formState.categoriaId.length === 0) {
|
||||
if (formState.categoryId.length === 0) {
|
||||
const message = "Selecione uma categoria.";
|
||||
setErrorMessage(message);
|
||||
toast.error(message);
|
||||
@@ -135,7 +135,7 @@ export function BudgetDialog({
|
||||
}
|
||||
|
||||
const payload = {
|
||||
categoriaId: formState.categoriaId,
|
||||
categoryId: formState.categoryId,
|
||||
period: formState.period,
|
||||
amount: formState.amount,
|
||||
};
|
||||
@@ -207,10 +207,10 @@ export function BudgetDialog({
|
||||
) : (
|
||||
<form className="space-y-4" onSubmit={handleSubmit}>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="budget-category">Categoria</Label>
|
||||
<Label htmlFor="budget-category">Category</Label>
|
||||
<Select
|
||||
value={formState.categoriaId}
|
||||
onValueChange={(value) => updateField("categoriaId", value)}
|
||||
value={formState.categoryId}
|
||||
onValueChange={(value) => updateField("categoryId", value)}
|
||||
>
|
||||
<SelectTrigger id="budget-category" className="w-full">
|
||||
<SelectValue placeholder="Selecione uma categoria" />
|
||||
|
||||
@@ -14,7 +14,7 @@ export type Budget = {
|
||||
};
|
||||
|
||||
export type BudgetFormValues = {
|
||||
categoriaId: string;
|
||||
categoryId: string;
|
||||
period: string;
|
||||
amount: string;
|
||||
};
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import { and, asc, eq, inArray, isNull, or, sql, sum } from "drizzle-orm";
|
||||
import {
|
||||
categorias,
|
||||
lancamentos,
|
||||
type Orcamento,
|
||||
orcamentos,
|
||||
pagadores,
|
||||
type Budget,
|
||||
budgets,
|
||||
categories,
|
||||
payers,
|
||||
transactions,
|
||||
} from "@/db/schema";
|
||||
import { ACCOUNT_AUTO_INVOICE_NOTE_PREFIX } from "@/shared/lib/accounts/constants";
|
||||
import { db } from "@/shared/lib/db";
|
||||
import { PAGADOR_ROLE_ADMIN } from "@/shared/lib/payers/constants";
|
||||
import { PAYER_ROLE_ADMIN } from "@/shared/lib/payers/constants";
|
||||
|
||||
const toNumber = (value: string | number | null | undefined) => {
|
||||
if (typeof value === "number") return value;
|
||||
@@ -46,28 +46,28 @@ export async function fetchBudgetsForUser(
|
||||
categoriesOptions: CategoryOption[];
|
||||
}> {
|
||||
const [budgetRows, categoryRows] = await Promise.all([
|
||||
db.query.orcamentos.findMany({
|
||||
db.query.budgets.findMany({
|
||||
where: and(
|
||||
eq(orcamentos.userId, userId),
|
||||
eq(orcamentos.period, selectedPeriod),
|
||||
eq(budgets.userId, userId),
|
||||
eq(budgets.period, selectedPeriod),
|
||||
),
|
||||
with: {
|
||||
categoria: true,
|
||||
category: true,
|
||||
},
|
||||
}),
|
||||
db.query.categorias.findMany({
|
||||
db.query.categories.findMany({
|
||||
columns: {
|
||||
id: true,
|
||||
name: true,
|
||||
icon: true,
|
||||
},
|
||||
where: and(eq(categorias.userId, userId), eq(categorias.type, "despesa")),
|
||||
orderBy: asc(categorias.name),
|
||||
where: and(eq(categories.userId, userId), eq(categories.type, "despesa")),
|
||||
orderBy: asc(categories.name),
|
||||
}),
|
||||
]);
|
||||
|
||||
const categoryIds = budgetRows
|
||||
.map((budget: Orcamento) => budget.categoriaId)
|
||||
.map((budget) => budget.categoryId)
|
||||
.filter((id: string | null): id is string => Boolean(id));
|
||||
|
||||
let totalsByCategory = new Map<string, number>();
|
||||
@@ -75,50 +75,48 @@ export async function fetchBudgetsForUser(
|
||||
if (categoryIds.length > 0) {
|
||||
const totals = await db
|
||||
.select({
|
||||
categoriaId: lancamentos.categoriaId,
|
||||
totalAmount: sum(lancamentos.amount).as("totalAmount"),
|
||||
categoryId: transactions.categoryId,
|
||||
totalAmount: sum(transactions.amount).as("totalAmount"),
|
||||
})
|
||||
.from(lancamentos)
|
||||
.innerJoin(pagadores, eq(lancamentos.pagadorId, pagadores.id))
|
||||
.from(transactions)
|
||||
.innerJoin(payers, eq(transactions.payerId, payers.id))
|
||||
.where(
|
||||
and(
|
||||
eq(lancamentos.userId, userId),
|
||||
eq(lancamentos.period, selectedPeriod),
|
||||
eq(lancamentos.transactionType, "Despesa"),
|
||||
eq(pagadores.role, PAGADOR_ROLE_ADMIN),
|
||||
inArray(lancamentos.categoriaId, categoryIds),
|
||||
eq(transactions.userId, userId),
|
||||
eq(transactions.period, selectedPeriod),
|
||||
eq(transactions.transactionType, "Despesa"),
|
||||
eq(payers.role, PAYER_ROLE_ADMIN),
|
||||
inArray(transactions.categoryId, categoryIds),
|
||||
or(
|
||||
isNull(lancamentos.note),
|
||||
sql`${lancamentos.note} NOT LIKE ${`${ACCOUNT_AUTO_INVOICE_NOTE_PREFIX}%`}`,
|
||||
isNull(transactions.note),
|
||||
sql`${transactions.note} NOT LIKE ${`${ACCOUNT_AUTO_INVOICE_NOTE_PREFIX}%`}`,
|
||||
),
|
||||
),
|
||||
)
|
||||
.groupBy(lancamentos.categoriaId);
|
||||
.groupBy(transactions.categoryId);
|
||||
|
||||
totalsByCategory = new Map(
|
||||
totals.map(
|
||||
(row: { categoriaId: string | null; totalAmount: string | null }) => [
|
||||
row.categoriaId ?? "",
|
||||
(row: { categoryId: string | null; totalAmount: string | null }) => [
|
||||
row.categoryId ?? "",
|
||||
Math.abs(toNumber(row.totalAmount)),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const budgets = budgetRows
|
||||
.map((budget: Orcamento) => ({
|
||||
const budgetList = budgetRows
|
||||
.map((budget) => ({
|
||||
id: budget.id,
|
||||
amount: toNumber(budget.amount),
|
||||
spent: totalsByCategory.get(budget.categoriaId ?? "") ?? 0,
|
||||
spent: totalsByCategory.get(budget.categoryId ?? "") ?? 0,
|
||||
period: budget.period,
|
||||
createdAt: budget.createdAt.toISOString(),
|
||||
category: budget.categoria
|
||||
? {
|
||||
id: budget.categoria.id,
|
||||
name: budget.categoria.name,
|
||||
icon: budget.categoria.icon,
|
||||
}
|
||||
: null,
|
||||
category: (() => {
|
||||
type Cat = { id: string; name: string; icon: string | null };
|
||||
const cat = budget.category as Cat | null | undefined;
|
||||
return cat ? { id: cat.id, name: cat.name, icon: cat.icon } : null;
|
||||
})(),
|
||||
}))
|
||||
.sort((a, b) =>
|
||||
(a.category?.name ?? "").localeCompare(b.category?.name ?? "", "pt-BR", {
|
||||
@@ -132,5 +130,5 @@ export async function fetchBudgetsForUser(
|
||||
icon: category.icon,
|
||||
}));
|
||||
|
||||
return { budgets, categoriesOptions };
|
||||
return { budgets: budgetList, categoriesOptions };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user