mirror of
https://github.com/felipegcoutinho/openmonetis.git
synced 2026-05-09 11:01:45 +00:00
fix(lancamentos): bloquear criação em fatura já paga no cartão de crédito
Evita divergência no relatório de análise de parcelas ao impedir o cadastro de lançamentos em períodos cujas faturas já foram quitadas. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -1,11 +1,18 @@
|
|||||||
"use server";
|
"use server";
|
||||||
|
|
||||||
import { randomUUID } from "node:crypto";
|
import { randomUUID } from "node:crypto";
|
||||||
import { and, eq } from "drizzle-orm";
|
import { and, eq, inArray } from "drizzle-orm";
|
||||||
import { financialAccounts, transactions } from "@/db/schema";
|
import {
|
||||||
|
attachments,
|
||||||
|
financialAccounts,
|
||||||
|
invoices,
|
||||||
|
transactionAttachments,
|
||||||
|
transactions,
|
||||||
|
} from "@/db/schema";
|
||||||
import { handleActionError } from "@/shared/lib/actions/helpers";
|
import { handleActionError } from "@/shared/lib/actions/helpers";
|
||||||
import { getUser } from "@/shared/lib/auth/server";
|
import { getUser } from "@/shared/lib/auth/server";
|
||||||
import { db } from "@/shared/lib/db";
|
import { db } from "@/shared/lib/db";
|
||||||
|
import { INVOICE_PAYMENT_STATUS } from "@/shared/lib/invoices";
|
||||||
import {
|
import {
|
||||||
buildEntriesByPayer,
|
buildEntriesByPayer,
|
||||||
sendPayerAutoEmails,
|
sendPayerAutoEmails,
|
||||||
@@ -16,6 +23,8 @@ import {
|
|||||||
getBusinessTodayDate,
|
getBusinessTodayDate,
|
||||||
parseLocalDateString,
|
parseLocalDateString,
|
||||||
} from "@/shared/utils/date";
|
} from "@/shared/utils/date";
|
||||||
|
import { MONTH_NAMES } from "@/shared/utils/period";
|
||||||
|
import { cleanupAttachmentsAfterTransactionDelete } from "./attachments";
|
||||||
import {
|
import {
|
||||||
buildLancamentoRecords,
|
buildLancamentoRecords,
|
||||||
buildShares,
|
buildShares,
|
||||||
@@ -37,7 +46,7 @@ import {
|
|||||||
|
|
||||||
export async function createTransactionAction(
|
export async function createTransactionAction(
|
||||||
input: CreateInput,
|
input: CreateInput,
|
||||||
): Promise<ActionResult> {
|
): Promise<ActionResult<{ ids: string[] }>> {
|
||||||
try {
|
try {
|
||||||
const user = await getUser();
|
const user = await getUser();
|
||||||
const data = createSchema.parse(input);
|
const data = createSchema.parse(input);
|
||||||
@@ -102,7 +111,42 @@ export async function createTransactionAction(
|
|||||||
throw new Error("Não foi possível criar os lançamentos solicitados.");
|
throw new Error("Não foi possível criar os lançamentos solicitados.");
|
||||||
}
|
}
|
||||||
|
|
||||||
await db.insert(transactions).values(records);
|
if (data.cardId) {
|
||||||
|
const uniquePeriods = [
|
||||||
|
...new Set(
|
||||||
|
records.map((r) => r.period).filter((p): p is string => Boolean(p)),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
|
||||||
|
const paidInvoices = await db.query.invoices.findMany({
|
||||||
|
columns: { period: true },
|
||||||
|
where: and(
|
||||||
|
eq(invoices.userId, user.id),
|
||||||
|
eq(invoices.cardId, data.cardId),
|
||||||
|
eq(invoices.paymentStatus, INVOICE_PAYMENT_STATUS.PAID),
|
||||||
|
inArray(invoices.period, uniquePeriods),
|
||||||
|
),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (paidInvoices.length > 0) {
|
||||||
|
const labels = paidInvoices
|
||||||
|
.map((inv) => {
|
||||||
|
const [year, month] = (inv.period ?? "").split("-");
|
||||||
|
const monthName = MONTH_NAMES[Number(month) - 1] ?? month;
|
||||||
|
return `${monthName}/${year}`;
|
||||||
|
})
|
||||||
|
.join(", ");
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: `As faturas dos meses ${labels} já estão pagas. Desfaça o pagamento antes de adicionar este lançamento.`,
|
||||||
|
} as ActionResult<{ ids: string[] }>;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const inserted = await db
|
||||||
|
.insert(transactions)
|
||||||
|
.values(records)
|
||||||
|
.returning({ id: transactions.id });
|
||||||
|
|
||||||
const notificationEntries = buildEntriesByPayer(
|
const notificationEntries = buildEntriesByPayer(
|
||||||
records.map((record) => ({
|
records.map((record) => ({
|
||||||
@@ -128,9 +172,13 @@ export async function createTransactionAction(
|
|||||||
|
|
||||||
revalidate(user.id);
|
revalidate(user.id);
|
||||||
|
|
||||||
return { success: true, message: "Lançamento criado com sucesso." };
|
return {
|
||||||
|
success: true,
|
||||||
|
message: "Lançamento criado com sucesso.",
|
||||||
|
data: { ids: inserted.map((r) => r.id) },
|
||||||
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return handleActionError(error);
|
return handleActionError(error) as ActionResult<{ ids: string[] }>;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -329,12 +377,23 @@ export async function deleteTransactionAction(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const linkedAttachments = await db
|
||||||
|
.select({ id: attachments.id, fileKey: attachments.fileKey })
|
||||||
|
.from(transactionAttachments)
|
||||||
|
.innerJoin(
|
||||||
|
attachments,
|
||||||
|
eq(transactionAttachments.attachmentId, attachments.id),
|
||||||
|
)
|
||||||
|
.where(eq(transactionAttachments.transactionId, data.id));
|
||||||
|
|
||||||
await db
|
await db
|
||||||
.delete(transactions)
|
.delete(transactions)
|
||||||
.where(
|
.where(
|
||||||
and(eq(transactions.id, data.id), eq(transactions.userId, user.id)),
|
and(eq(transactions.id, data.id), eq(transactions.userId, user.id)),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
await cleanupAttachmentsAfterTransactionDelete(linkedAttachments);
|
||||||
|
|
||||||
if (existing.payerId) {
|
if (existing.payerId) {
|
||||||
const notificationEntries = buildEntriesByPayer([
|
const notificationEntries = buildEntriesByPayer([
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -6,6 +6,10 @@ import {
|
|||||||
createTransactionAction,
|
createTransactionAction,
|
||||||
updateTransactionAction,
|
updateTransactionAction,
|
||||||
} from "@/features/transactions/actions";
|
} from "@/features/transactions/actions";
|
||||||
|
import {
|
||||||
|
confirmAttachmentUploadAction,
|
||||||
|
getPresignedUploadUrlAction,
|
||||||
|
} from "@/features/transactions/actions/attachments";
|
||||||
import {
|
import {
|
||||||
filterSecondaryPayerOptions,
|
filterSecondaryPayerOptions,
|
||||||
groupAndSortCategories,
|
groupAndSortCategories,
|
||||||
@@ -30,7 +34,10 @@ import {
|
|||||||
DialogTitle,
|
DialogTitle,
|
||||||
DialogTrigger,
|
DialogTrigger,
|
||||||
} from "@/shared/components/ui/dialog";
|
} from "@/shared/components/ui/dialog";
|
||||||
|
import { Label } from "@/shared/components/ui/label";
|
||||||
import { useControlledState } from "@/shared/hooks/use-controlled-state";
|
import { useControlledState } from "@/shared/hooks/use-controlled-state";
|
||||||
|
import { AttachmentFilePicker } from "../../attachments/attachment-file-picker";
|
||||||
|
import { AttachmentSection } from "../../attachments/attachment-section";
|
||||||
import { BasicFieldsSection } from "./basic-fields-section";
|
import { BasicFieldsSection } from "./basic-fields-section";
|
||||||
import { BoletoFieldsSection } from "./boleto-fields-section";
|
import { BoletoFieldsSection } from "./boleto-fields-section";
|
||||||
import { CategorySection } from "./category-section";
|
import { CategorySection } from "./category-section";
|
||||||
@@ -90,6 +97,7 @@ export function TransactionDialog({
|
|||||||
);
|
);
|
||||||
const [isPending, startTransition] = useTransition();
|
const [isPending, startTransition] = useTransition();
|
||||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||||
|
const [pendingFile, setPendingFile] = useState<File | null>(null);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (dialogOpen) {
|
if (dialogOpen) {
|
||||||
@@ -126,6 +134,7 @@ export function TransactionDialog({
|
|||||||
|
|
||||||
setFormState(initial);
|
setFormState(initial);
|
||||||
setErrorMessage(null);
|
setErrorMessage(null);
|
||||||
|
setPendingFile(null);
|
||||||
}
|
}
|
||||||
}, [
|
}, [
|
||||||
dialogOpen,
|
dialogOpen,
|
||||||
@@ -313,6 +322,29 @@ export function TransactionDialog({
|
|||||||
const result = await createTransactionAction(payload);
|
const result = await createTransactionAction(payload);
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
|
if (pendingFile && result.data?.ids?.length) {
|
||||||
|
const firstId = result.data.ids[0];
|
||||||
|
const isNewSeries =
|
||||||
|
formState.condition === "Parcelado" ||
|
||||||
|
formState.condition === "Recorrente";
|
||||||
|
const presign = await getPresignedUploadUrlAction({
|
||||||
|
fileName: pendingFile.name,
|
||||||
|
mimeType: pendingFile.type,
|
||||||
|
fileSize: pendingFile.size,
|
||||||
|
transactionId: firstId,
|
||||||
|
});
|
||||||
|
if (presign.success) {
|
||||||
|
await fetch(presign.presignedUrl, {
|
||||||
|
method: "PUT",
|
||||||
|
body: pendingFile,
|
||||||
|
headers: { "Content-Type": pendingFile.type },
|
||||||
|
});
|
||||||
|
await confirmAttachmentUploadAction({
|
||||||
|
uploadToken: presign.uploadToken,
|
||||||
|
applyToSeries: isNewSeries,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
toast.success(result.message);
|
toast.success(result.message);
|
||||||
onSuccess?.();
|
onSuccess?.();
|
||||||
setDialogOpen(false);
|
setDialogOpen(false);
|
||||||
@@ -415,18 +447,18 @@ export function TransactionDialog({
|
|||||||
return (
|
return (
|
||||||
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
|
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
|
||||||
{trigger ? <DialogTrigger asChild>{trigger}</DialogTrigger> : null}
|
{trigger ? <DialogTrigger asChild>{trigger}</DialogTrigger> : null}
|
||||||
<DialogContent>
|
<DialogContent className="min-w-0 overflow-x-hidden">
|
||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
<DialogTitle>{title}</DialogTitle>
|
<DialogTitle>{title}</DialogTitle>
|
||||||
<DialogDescription>{description}</DialogDescription>
|
<DialogDescription>{description}</DialogDescription>
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
|
|
||||||
<form
|
<form
|
||||||
className="flex flex-col gap-0"
|
className="flex min-w-0 flex-col gap-0"
|
||||||
onSubmit={handleSubmit}
|
onSubmit={handleSubmit}
|
||||||
noValidate
|
noValidate
|
||||||
>
|
>
|
||||||
<div className="space-y-3 -mx-6 max-h-[70vh] overflow-y-auto px-6 pb-1">
|
<div className="min-w-0 space-y-3 -mx-6 max-h-[90vh] overflow-x-hidden overflow-y-auto px-6 pb-1">
|
||||||
<BasicFieldsSection
|
<BasicFieldsSection
|
||||||
formState={formState}
|
formState={formState}
|
||||||
onFieldChange={handleFieldChange}
|
onFieldChange={handleFieldChange}
|
||||||
@@ -477,17 +509,31 @@ export function TransactionDialog({
|
|||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{isUpdateMode ? (
|
{isUpdateMode ? (
|
||||||
<NoteSection
|
<>
|
||||||
formState={formState}
|
<NoteSection
|
||||||
onFieldChange={handleFieldChange}
|
formState={formState}
|
||||||
/>
|
onFieldChange={handleFieldChange}
|
||||||
|
/>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label className="text-xs font-medium leading-none">
|
||||||
|
Anexos
|
||||||
|
</Label>
|
||||||
|
<AttachmentSection
|
||||||
|
transactionId={transaction?.id ?? ""}
|
||||||
|
seriesId={transaction?.seriesId ?? null}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
) : (
|
) : (
|
||||||
<Collapsible defaultOpen={formState.condition !== "À vista"}>
|
<Collapsible
|
||||||
|
defaultOpen={formState.condition !== "À vista"}
|
||||||
|
className="min-w-0"
|
||||||
|
>
|
||||||
<CollapsibleTrigger className="flex w-full items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors cursor-pointer [&[data-state=open]>svg]:rotate-180 mt-4">
|
<CollapsibleTrigger className="flex w-full items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors cursor-pointer [&[data-state=open]>svg]:rotate-180 mt-4">
|
||||||
<RiArrowDropDownLine className="text-primary size-4 transition-transform duration-200" />
|
<RiArrowDropDownLine className="text-primary size-4 transition-transform duration-200" />
|
||||||
Condições e anotações
|
Condições, anotações e anexos
|
||||||
</CollapsibleTrigger>
|
</CollapsibleTrigger>
|
||||||
<CollapsibleContent className="space-y-3 pt-3">
|
<CollapsibleContent className="min-w-0 overflow-hidden space-y-3 pt-3">
|
||||||
<ConditionSection
|
<ConditionSection
|
||||||
formState={formState}
|
formState={formState}
|
||||||
onFieldChange={handleFieldChange}
|
onFieldChange={handleFieldChange}
|
||||||
@@ -498,6 +544,10 @@ export function TransactionDialog({
|
|||||||
formState={formState}
|
formState={formState}
|
||||||
onFieldChange={handleFieldChange}
|
onFieldChange={handleFieldChange}
|
||||||
/>
|
/>
|
||||||
|
<AttachmentFilePicker
|
||||||
|
file={pendingFile}
|
||||||
|
onChange={setPendingFile}
|
||||||
|
/>
|
||||||
</CollapsibleContent>
|
</CollapsibleContent>
|
||||||
</Collapsible>
|
</Collapsible>
|
||||||
)}
|
)}
|
||||||
|
|||||||
Reference in New Issue
Block a user