mirror of
https://github.com/felipegcoutinho/openmonetis.git
synced 2026-05-09 02:51:46 +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";
|
||||
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { financialAccounts, transactions } from "@/db/schema";
|
||||
import { and, eq, inArray } from "drizzle-orm";
|
||||
import {
|
||||
attachments,
|
||||
financialAccounts,
|
||||
invoices,
|
||||
transactionAttachments,
|
||||
transactions,
|
||||
} from "@/db/schema";
|
||||
import { handleActionError } from "@/shared/lib/actions/helpers";
|
||||
import { getUser } from "@/shared/lib/auth/server";
|
||||
import { db } from "@/shared/lib/db";
|
||||
import { INVOICE_PAYMENT_STATUS } from "@/shared/lib/invoices";
|
||||
import {
|
||||
buildEntriesByPayer,
|
||||
sendPayerAutoEmails,
|
||||
@@ -16,6 +23,8 @@ import {
|
||||
getBusinessTodayDate,
|
||||
parseLocalDateString,
|
||||
} from "@/shared/utils/date";
|
||||
import { MONTH_NAMES } from "@/shared/utils/period";
|
||||
import { cleanupAttachmentsAfterTransactionDelete } from "./attachments";
|
||||
import {
|
||||
buildLancamentoRecords,
|
||||
buildShares,
|
||||
@@ -37,7 +46,7 @@ import {
|
||||
|
||||
export async function createTransactionAction(
|
||||
input: CreateInput,
|
||||
): Promise<ActionResult> {
|
||||
): Promise<ActionResult<{ ids: string[] }>> {
|
||||
try {
|
||||
const user = await getUser();
|
||||
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.");
|
||||
}
|
||||
|
||||
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(
|
||||
records.map((record) => ({
|
||||
@@ -128,9 +172,13 @@ export async function createTransactionAction(
|
||||
|
||||
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) {
|
||||
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
|
||||
.delete(transactions)
|
||||
.where(
|
||||
and(eq(transactions.id, data.id), eq(transactions.userId, user.id)),
|
||||
);
|
||||
|
||||
await cleanupAttachmentsAfterTransactionDelete(linkedAttachments);
|
||||
|
||||
if (existing.payerId) {
|
||||
const notificationEntries = buildEntriesByPayer([
|
||||
{
|
||||
|
||||
@@ -6,6 +6,10 @@ import {
|
||||
createTransactionAction,
|
||||
updateTransactionAction,
|
||||
} from "@/features/transactions/actions";
|
||||
import {
|
||||
confirmAttachmentUploadAction,
|
||||
getPresignedUploadUrlAction,
|
||||
} from "@/features/transactions/actions/attachments";
|
||||
import {
|
||||
filterSecondaryPayerOptions,
|
||||
groupAndSortCategories,
|
||||
@@ -30,7 +34,10 @@ import {
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/shared/components/ui/dialog";
|
||||
import { Label } from "@/shared/components/ui/label";
|
||||
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 { BoletoFieldsSection } from "./boleto-fields-section";
|
||||
import { CategorySection } from "./category-section";
|
||||
@@ -90,6 +97,7 @@ export function TransactionDialog({
|
||||
);
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
const [pendingFile, setPendingFile] = useState<File | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (dialogOpen) {
|
||||
@@ -126,6 +134,7 @@ export function TransactionDialog({
|
||||
|
||||
setFormState(initial);
|
||||
setErrorMessage(null);
|
||||
setPendingFile(null);
|
||||
}
|
||||
}, [
|
||||
dialogOpen,
|
||||
@@ -313,6 +322,29 @@ export function TransactionDialog({
|
||||
const result = await createTransactionAction(payload);
|
||||
|
||||
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);
|
||||
onSuccess?.();
|
||||
setDialogOpen(false);
|
||||
@@ -415,18 +447,18 @@ export function TransactionDialog({
|
||||
return (
|
||||
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
|
||||
{trigger ? <DialogTrigger asChild>{trigger}</DialogTrigger> : null}
|
||||
<DialogContent>
|
||||
<DialogContent className="min-w-0 overflow-x-hidden">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
<DialogDescription>{description}</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<form
|
||||
className="flex flex-col gap-0"
|
||||
className="flex min-w-0 flex-col gap-0"
|
||||
onSubmit={handleSubmit}
|
||||
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
|
||||
formState={formState}
|
||||
onFieldChange={handleFieldChange}
|
||||
@@ -477,17 +509,31 @@ export function TransactionDialog({
|
||||
) : null}
|
||||
|
||||
{isUpdateMode ? (
|
||||
<NoteSection
|
||||
formState={formState}
|
||||
onFieldChange={handleFieldChange}
|
||||
/>
|
||||
<>
|
||||
<NoteSection
|
||||
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">
|
||||
<RiArrowDropDownLine className="text-primary size-4 transition-transform duration-200" />
|
||||
Condições e anotações
|
||||
Condições, anotações e anexos
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent className="space-y-3 pt-3">
|
||||
<CollapsibleContent className="min-w-0 overflow-hidden space-y-3 pt-3">
|
||||
<ConditionSection
|
||||
formState={formState}
|
||||
onFieldChange={handleFieldChange}
|
||||
@@ -498,6 +544,10 @@ export function TransactionDialog({
|
||||
formState={formState}
|
||||
onFieldChange={handleFieldChange}
|
||||
/>
|
||||
<AttachmentFilePicker
|
||||
file={pendingFile}
|
||||
onChange={setPendingFile}
|
||||
/>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
)}
|
||||
|
||||
Reference in New Issue
Block a user