mirror of
https://github.com/felipegcoutinho/openmonetis.git
synced 2026-05-09 19:01:47 +00:00
refactor(core): move app para src e padroniza estrutura
This commit is contained in:
42
src/features/calendar/components/calendar-grid.tsx
Normal file
42
src/features/calendar/components/calendar-grid.tsx
Normal file
@@ -0,0 +1,42 @@
|
||||
"use client";
|
||||
|
||||
import { DayCell } from "@/features/calendar/components/day-cell";
|
||||
|
||||
import type { CalendarDay } from "@/shared/lib/types/calendar";
|
||||
import { WEEK_DAYS_SHORT } from "@/shared/utils/calendar";
|
||||
import { cn } from "@/shared/utils/ui";
|
||||
|
||||
type CalendarGridProps = {
|
||||
days: CalendarDay[];
|
||||
onSelectDay: (day: CalendarDay) => void;
|
||||
onCreateDay: (day: CalendarDay) => void;
|
||||
};
|
||||
|
||||
export function CalendarGrid({
|
||||
days,
|
||||
onSelectDay,
|
||||
onCreateDay,
|
||||
}: CalendarGridProps) {
|
||||
return (
|
||||
<div className="overflow-hidden rounded-lg bg-card drop-shadow-xs border-none">
|
||||
<div className="grid grid-cols-7 text-sm font-semibold uppercase tracking-wide text-muted-foreground">
|
||||
{WEEK_DAYS_SHORT.map((dayName) => (
|
||||
<span key={dayName} className="px-3 py-2 text-center text-primary">
|
||||
{dayName}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-7 gap-px bg-border/60 px-px pb-px pt-px">
|
||||
{days.map((day) => (
|
||||
<div
|
||||
key={day.date}
|
||||
className={cn("h-[150px] bg-card p-0.5", !day.isCurrentMonth && "")}
|
||||
>
|
||||
<DayCell day={day} onSelect={onSelectDay} onCreate={onCreateDay} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
34
src/features/calendar/components/calendar-legend.tsx
Normal file
34
src/features/calendar/components/calendar-legend.tsx
Normal file
@@ -0,0 +1,34 @@
|
||||
"use client";
|
||||
|
||||
import { EVENT_TYPE_STYLES } from "@/features/calendar/components/day-cell";
|
||||
import StatusDot from "@/shared/components/status-dot";
|
||||
import { Card } from "@/shared/components/ui/card";
|
||||
import type { CalendarEvent } from "@/shared/lib/types/calendar";
|
||||
|
||||
const LEGEND_ITEMS: Array<{
|
||||
type?: CalendarEvent["type"];
|
||||
label: string;
|
||||
dotColor?: string;
|
||||
}> = [
|
||||
{ type: "lancamento", label: "Lançamentos" },
|
||||
{ type: "boleto", label: "Boleto com vencimento" },
|
||||
{ type: "cartao", label: "Vencimento de cartão" },
|
||||
{ label: "Pagamento fatura", dotColor: "bg-success" },
|
||||
];
|
||||
|
||||
export function CalendarLegend() {
|
||||
return (
|
||||
<Card className="flex flex-row gap-2 p-2 text-sm">
|
||||
{LEGEND_ITEMS.map((item, index) => {
|
||||
const dotColor =
|
||||
item.dotColor || (item.type ? EVENT_TYPE_STYLES[item.type].dot : "");
|
||||
return (
|
||||
<span key={item.type || index} className="flex items-center gap-2">
|
||||
<StatusDot color={dotColor} />
|
||||
{item.label}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
185
src/features/calendar/components/day-cell.tsx
Normal file
185
src/features/calendar/components/day-cell.tsx
Normal file
@@ -0,0 +1,185 @@
|
||||
"use client";
|
||||
|
||||
import { RiAddLine } from "@remixicon/react";
|
||||
import type { KeyboardEvent, MouseEvent } from "react";
|
||||
import type { CalendarDay, CalendarEvent } from "@/shared/lib/types/calendar";
|
||||
import { currencyFormatter } from "@/shared/utils/currency";
|
||||
import { cn } from "@/shared/utils/ui";
|
||||
|
||||
type DayCellProps = {
|
||||
day: CalendarDay;
|
||||
onSelect: (day: CalendarDay) => void;
|
||||
onCreate: (day: CalendarDay) => void;
|
||||
};
|
||||
|
||||
export const EVENT_TYPE_STYLES: Record<
|
||||
CalendarEvent["type"],
|
||||
{ wrapper: string; dot: string; accent?: string }
|
||||
> = {
|
||||
lancamento: {
|
||||
wrapper:
|
||||
"bg-warning/10 text-warning dark:bg-warning/5 dark:text-warning border-l-4 border-warning",
|
||||
dot: "bg-warning",
|
||||
},
|
||||
boleto: {
|
||||
wrapper:
|
||||
"bg-info/10 text-info dark:bg-info/5 dark:text-info border-l-4 border-info",
|
||||
dot: "bg-info",
|
||||
},
|
||||
cartao: {
|
||||
wrapper:
|
||||
"bg-violet-100 text-violet-600 dark:bg-violet-900/10 dark:text-violet-50 border-l-4 border-violet-500",
|
||||
dot: "bg-violet-600",
|
||||
},
|
||||
};
|
||||
|
||||
const eventStyles = EVENT_TYPE_STYLES;
|
||||
|
||||
const formatCurrencyValue = (value: number | null | undefined) =>
|
||||
currencyFormatter.format(Math.abs(value ?? 0));
|
||||
|
||||
const formatAmount = (event: Extract<CalendarEvent, { type: "lancamento" }>) =>
|
||||
formatCurrencyValue(event.lancamento.amount);
|
||||
|
||||
const buildEventLabel = (event: CalendarEvent) => {
|
||||
switch (event.type) {
|
||||
case "lancamento": {
|
||||
return event.lancamento.name;
|
||||
}
|
||||
case "boleto": {
|
||||
return event.lancamento.name;
|
||||
}
|
||||
case "cartao": {
|
||||
return event.card.name;
|
||||
}
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
};
|
||||
|
||||
const buildEventComplement = (event: CalendarEvent) => {
|
||||
switch (event.type) {
|
||||
case "lancamento": {
|
||||
return formatAmount(event);
|
||||
}
|
||||
case "boleto": {
|
||||
return formatCurrencyValue(event.lancamento.amount);
|
||||
}
|
||||
case "cartao": {
|
||||
if (event.card.totalDue !== null) {
|
||||
return formatCurrencyValue(event.card.totalDue);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const isPagamentoFatura = (event: CalendarEvent) => {
|
||||
return (
|
||||
event.type === "lancamento" &&
|
||||
event.lancamento.name.startsWith("Pagamento fatura -")
|
||||
);
|
||||
};
|
||||
|
||||
const getEventStyle = (event: CalendarEvent) => {
|
||||
if (isPagamentoFatura(event)) {
|
||||
return {
|
||||
wrapper:
|
||||
"bg-success/10 text-success dark:bg-success/5 dark:text-success border-l-4 border-success",
|
||||
dot: "bg-success",
|
||||
};
|
||||
}
|
||||
return eventStyles[event.type];
|
||||
};
|
||||
|
||||
const DayEventPreview = ({ event }: { event: CalendarEvent }) => {
|
||||
const complement = buildEventComplement(event);
|
||||
const label = buildEventLabel(event);
|
||||
const style = getEventStyle(event);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex w-full items-center justify-between gap-2 rounded p-1 text-xs",
|
||||
style.wrapper,
|
||||
)}
|
||||
>
|
||||
<div className="flex min-w-0 items-center gap-1">
|
||||
<span className="truncate">{label}</span>
|
||||
</div>
|
||||
{complement ? (
|
||||
<span
|
||||
className={cn("shrink-0 font-semibold", style.accent ?? "text-xs")}
|
||||
>
|
||||
{complement}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export function DayCell({ day, onSelect, onCreate }: DayCellProps) {
|
||||
const previewEvents = day.events.slice(0, 3);
|
||||
const hasOverflow = day.events.length > 3;
|
||||
|
||||
const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
|
||||
if (event.key === "Enter" || event.key === " " || event.key === "Space") {
|
||||
event.preventDefault();
|
||||
onSelect(day);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCreateClick = (event: MouseEvent<HTMLButtonElement>) => {
|
||||
event.stopPropagation();
|
||||
onCreate(day);
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={() => onSelect(day)}
|
||||
onKeyDown={handleKeyDown}
|
||||
className={cn(
|
||||
"flex h-full cursor-pointer flex-col gap-1.5 rounded-lg border border-transparent bg-card/80 p-2 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 hover:border-primary/40 hover:bg-primary/5 dark:hover:bg-primary/10",
|
||||
!day.isCurrentMonth && "opacity-60",
|
||||
day.isToday && "border-primary/70 bg-primary/5 hover:border-primary",
|
||||
)}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<span
|
||||
className={cn(
|
||||
"text-sm font-semibold leading-none",
|
||||
day.isToday
|
||||
? "text-orange-100 bg-primary size-5 rounded-full flex items-center justify-center"
|
||||
: "text-foreground/90",
|
||||
)}
|
||||
>
|
||||
{day.label}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleCreateClick}
|
||||
className="flex size-6 items-center justify-center rounded-full border bg-muted text-muted-foreground transition-colors hover:bg-primary/20 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-1"
|
||||
aria-label={`Criar lançamento em ${day.date}`}
|
||||
>
|
||||
<RiAddLine className="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-1 flex-col gap-1.5">
|
||||
{previewEvents.map((event) => (
|
||||
<DayEventPreview key={event.id} event={event} />
|
||||
))}
|
||||
|
||||
{hasOverflow ? (
|
||||
<span className="text-xs font-medium text-primary/80">
|
||||
+ ver mais
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
211
src/features/calendar/components/event-modal.tsx
Normal file
211
src/features/calendar/components/event-modal.tsx
Normal file
@@ -0,0 +1,211 @@
|
||||
"use client";
|
||||
|
||||
import type { ReactNode } from "react";
|
||||
import { EVENT_TYPE_STYLES } from "@/features/calendar/components/day-cell";
|
||||
import MoneyValues from "@/shared/components/money-values";
|
||||
import { Badge } from "@/shared/components/ui/badge";
|
||||
import { Button } from "@/shared/components/ui/button";
|
||||
import { Card } from "@/shared/components/ui/card";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/shared/components/ui/dialog";
|
||||
import type { CalendarDay, CalendarEvent } from "@/shared/lib/types/calendar";
|
||||
import { friendlyDate, parseLocalDateString } from "@/shared/utils/date";
|
||||
import { formatFinancialDateLabel } from "@/shared/utils/financial-dates";
|
||||
import { cn } from "@/shared/utils/ui";
|
||||
|
||||
type EventModalProps = {
|
||||
open: boolean;
|
||||
day: CalendarDay | null;
|
||||
onClose: () => void;
|
||||
onCreate: (date: string) => void;
|
||||
};
|
||||
|
||||
const EventCard = ({
|
||||
children,
|
||||
type,
|
||||
isPagamentoFatura = false,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
type: CalendarEvent["type"];
|
||||
isPagamentoFatura?: boolean;
|
||||
}) => {
|
||||
const style = isPagamentoFatura
|
||||
? { dot: "bg-success" }
|
||||
: EVENT_TYPE_STYLES[type];
|
||||
return (
|
||||
<Card className="flex flex-row gap-2 p-3 mb-1">
|
||||
<span
|
||||
className={cn("mt-1 size-3 shrink-0 rounded-full", style.dot)}
|
||||
aria-hidden
|
||||
/>
|
||||
<div className="flex flex-1 flex-col">{children}</div>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
const renderLancamento = (
|
||||
event: Extract<CalendarEvent, { type: "lancamento" }>,
|
||||
) => {
|
||||
const isReceita = event.lancamento.transactionType === "Receita";
|
||||
const isPagamentoFatura =
|
||||
event.lancamento.name.startsWith("Pagamento fatura -");
|
||||
|
||||
return (
|
||||
<EventCard type="lancamento" isPagamentoFatura={isPagamentoFatura}>
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="flex flex-col gap-1">
|
||||
<span
|
||||
className={`text-sm font-semibold leading-tight ${
|
||||
isPagamentoFatura && "text-success"
|
||||
}`}
|
||||
>
|
||||
{event.lancamento.name}
|
||||
</span>
|
||||
|
||||
<div className="flex gap-1">
|
||||
<Badge variant={"outline"}>{event.lancamento.condition}</Badge>
|
||||
<Badge variant={"outline"}>{event.lancamento.paymentMethod}</Badge>
|
||||
<Badge variant={"outline"}>{event.lancamento.categoriaName}</Badge>
|
||||
</div>
|
||||
</div>
|
||||
<span
|
||||
className={cn(
|
||||
"text-sm font-semibold whitespace-nowrap",
|
||||
isReceita ? "text-success" : "text-foreground",
|
||||
)}
|
||||
>
|
||||
<MoneyValues
|
||||
showPositiveSign
|
||||
className="text-base"
|
||||
amount={event.lancamento.amount}
|
||||
/>
|
||||
</span>
|
||||
</div>
|
||||
</EventCard>
|
||||
);
|
||||
};
|
||||
|
||||
const renderBoleto = (event: Extract<CalendarEvent, { type: "boleto" }>) => {
|
||||
const isPaid = Boolean(event.lancamento.isSettled);
|
||||
const dueDate = event.lancamento.dueDate;
|
||||
const dueDateLabel = formatFinancialDateLabel(dueDate, "Vence em", {
|
||||
day: "2-digit",
|
||||
month: "2-digit",
|
||||
year: "numeric",
|
||||
});
|
||||
|
||||
return (
|
||||
<EventCard type="boleto">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="flex flex-col gap-1">
|
||||
<div className="flex gap-1 items-center">
|
||||
<span className="text-sm font-semibold leading-tight">
|
||||
{event.lancamento.name}
|
||||
</span>
|
||||
|
||||
{dueDateLabel && (
|
||||
<span className="text-xs text-muted-foreground leading-tight">
|
||||
{dueDateLabel}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Badge variant={"outline"}>{isPaid ? "Pago" : "Pendente"}</Badge>
|
||||
</div>
|
||||
<span className="font-semibold">
|
||||
<MoneyValues amount={event.lancamento.amount} />
|
||||
</span>
|
||||
</div>
|
||||
</EventCard>
|
||||
);
|
||||
};
|
||||
|
||||
const renderCard = (event: Extract<CalendarEvent, { type: "cartao" }>) => (
|
||||
<EventCard type="cartao">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="flex flex-col gap-1">
|
||||
<div className="flex gap-1 items-center">
|
||||
<span className="text-sm font-semibold leading-tight">
|
||||
Vencimento Fatura - {event.card.name}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<Badge variant={"outline"}>{event.card.status ?? "Fatura"}</Badge>
|
||||
</div>
|
||||
{event.card.totalDue !== null ? (
|
||||
<span className="font-semibold">
|
||||
<MoneyValues amount={event.card.totalDue} />
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
</EventCard>
|
||||
);
|
||||
|
||||
const renderEvent = (event: CalendarEvent) => {
|
||||
switch (event.type) {
|
||||
case "lancamento":
|
||||
return renderLancamento(event);
|
||||
case "boleto":
|
||||
return renderBoleto(event);
|
||||
case "cartao":
|
||||
return renderCard(event);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
export function EventModal({ open, day, onClose, onCreate }: EventModalProps) {
|
||||
const formattedDate = !day
|
||||
? ""
|
||||
: friendlyDate(parseLocalDateString(day.date));
|
||||
|
||||
const handleCreate = () => {
|
||||
if (!day) return;
|
||||
onClose();
|
||||
onCreate(day.date);
|
||||
};
|
||||
|
||||
const description = day?.events.length
|
||||
? "Confira os lançamentos e vencimentos cadastrados para este dia."
|
||||
: "Nenhum lançamento encontrado para este dia. Você pode criar um novo lançamento agora.";
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(value) => (!value ? onClose() : null)}>
|
||||
<DialogContent className="max-w-xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{formattedDate}</DialogTitle>
|
||||
<DialogDescription>{description}</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="max-h-[380px] space-y-2 overflow-y-auto pr-2">
|
||||
{day?.events.length ? (
|
||||
day.events.map((event) => (
|
||||
<div key={event.id}>{renderEvent(event)}</div>
|
||||
))
|
||||
) : (
|
||||
<div className="rounded-xl border border-dashed border-border/60 bg-muted/30 p-6 text-center text-sm text-muted-foreground">
|
||||
Nenhum lançamento ou vencimento registrado. Clique em{" "}
|
||||
<span className="font-medium text-primary">Novo lançamento</span>{" "}
|
||||
para começar.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={onClose}>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button onClick={handleCreate} disabled={!day}>
|
||||
Novo lançamento
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
112
src/features/calendar/components/monthly-calendar.tsx
Normal file
112
src/features/calendar/components/monthly-calendar.tsx
Normal file
@@ -0,0 +1,112 @@
|
||||
"use client";
|
||||
|
||||
import { useMemo, useState } from "react";
|
||||
import { CalendarGrid } from "@/features/calendar/components/calendar-grid";
|
||||
import { CalendarLegend } from "@/features/calendar/components/calendar-legend";
|
||||
import { EventModal } from "@/features/calendar/components/event-modal";
|
||||
import { LancamentoDialog } from "@/features/transactions/components/dialogs/transaction-dialog/transaction-dialog";
|
||||
import type {
|
||||
CalendarDay,
|
||||
CalendarEvent,
|
||||
CalendarFormOptions,
|
||||
CalendarPeriod,
|
||||
} from "@/shared/lib/types/calendar";
|
||||
import { buildCalendarDays } from "@/shared/utils/calendar";
|
||||
import { parsePeriod } from "@/shared/utils/period";
|
||||
|
||||
type MonthlyCalendarProps = {
|
||||
period: CalendarPeriod;
|
||||
events: CalendarEvent[];
|
||||
formOptions: CalendarFormOptions;
|
||||
};
|
||||
|
||||
export function MonthlyCalendar({
|
||||
period,
|
||||
events,
|
||||
formOptions,
|
||||
}: MonthlyCalendarProps) {
|
||||
const { year, month } = parsePeriod(period.period);
|
||||
const monthIndex = month - 1;
|
||||
|
||||
const eventsByDay = useMemo(() => {
|
||||
const map = new Map<string, CalendarEvent[]>();
|
||||
events.forEach((event) => {
|
||||
const list = map.get(event.date) ?? [];
|
||||
list.push(event);
|
||||
map.set(event.date, list);
|
||||
});
|
||||
return map;
|
||||
}, [events]);
|
||||
|
||||
const days = useMemo(
|
||||
() => buildCalendarDays({ year, monthIndex, events: eventsByDay }),
|
||||
[eventsByDay, monthIndex, year],
|
||||
);
|
||||
|
||||
const [selectedDay, setSelectedDay] = useState<CalendarDay | null>(null);
|
||||
const [isModalOpen, setModalOpen] = useState(false);
|
||||
const [createOpen, setCreateOpen] = useState(false);
|
||||
const [createDate, setCreateDate] = useState<string | null>(null);
|
||||
|
||||
const handleOpenCreate = (date: string) => {
|
||||
setCreateDate(date);
|
||||
setModalOpen(false);
|
||||
setCreateOpen(true);
|
||||
};
|
||||
|
||||
const handleDaySelect = (day: CalendarDay) => {
|
||||
setSelectedDay(day);
|
||||
setModalOpen(true);
|
||||
};
|
||||
|
||||
const handleCreateFromCell = (day: CalendarDay) => {
|
||||
handleOpenCreate(day.date);
|
||||
};
|
||||
|
||||
const handleModalClose = () => {
|
||||
setModalOpen(false);
|
||||
setSelectedDay(null);
|
||||
};
|
||||
|
||||
const handleCreateDialogChange = (open: boolean) => {
|
||||
setCreateOpen(open);
|
||||
if (!open) {
|
||||
setCreateDate(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="space-y-3">
|
||||
<CalendarLegend />
|
||||
<CalendarGrid
|
||||
days={days}
|
||||
onSelectDay={handleDaySelect}
|
||||
onCreateDay={handleCreateFromCell}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<EventModal
|
||||
open={isModalOpen}
|
||||
day={selectedDay}
|
||||
onClose={handleModalClose}
|
||||
onCreate={handleOpenCreate}
|
||||
/>
|
||||
|
||||
<LancamentoDialog
|
||||
mode="create"
|
||||
open={createOpen}
|
||||
onOpenChange={handleCreateDialogChange}
|
||||
pagadorOptions={formOptions.pagadorOptions}
|
||||
splitPagadorOptions={formOptions.splitPagadorOptions}
|
||||
defaultPagadorId={formOptions.defaultPagadorId}
|
||||
contaOptions={formOptions.contaOptions}
|
||||
cartaoOptions={formOptions.cartaoOptions}
|
||||
categoriaOptions={formOptions.categoriaOptions}
|
||||
estabelecimentos={formOptions.estabelecimentos}
|
||||
defaultPeriod={period.period}
|
||||
defaultPurchaseDate={createDate ?? undefined}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
206
src/features/calendar/queries.ts
Normal file
206
src/features/calendar/queries.ts
Normal file
@@ -0,0 +1,206 @@
|
||||
import { and, eq, gte, lte, ne, or } from "drizzle-orm";
|
||||
import { cartoes, lancamentos } from "@/db/schema";
|
||||
import {
|
||||
buildOptionSets,
|
||||
buildSluggedFilters,
|
||||
mapLancamentosData,
|
||||
} from "@/features/transactions/page-helpers";
|
||||
import {
|
||||
fetchLancamentoFilterSources,
|
||||
fetchRecentEstablishments,
|
||||
} from "@/features/transactions/queries";
|
||||
import { db } from "@/shared/lib/db";
|
||||
import { PAGADOR_ROLE_ADMIN } from "@/shared/lib/payers/constants";
|
||||
import type { CalendarData, CalendarEvent } from "@/shared/lib/types/calendar";
|
||||
import { formatDateKey } from "@/shared/utils/calendar";
|
||||
import { parsePeriod } from "@/shared/utils/period";
|
||||
|
||||
const PAYMENT_METHOD_BOLETO = "Boleto";
|
||||
const TRANSACTION_TYPE_TRANSFERENCIA = "Transferência";
|
||||
|
||||
const clampDayInMonth = (year: number, monthIndex: number, day: number) => {
|
||||
const lastDay = new Date(Date.UTC(year, monthIndex + 1, 0)).getUTCDate();
|
||||
if (day < 1) return 1;
|
||||
if (day > lastDay) return lastDay;
|
||||
return day;
|
||||
};
|
||||
|
||||
const isWithinRange = (value: string | null, start: string, end: string) => {
|
||||
if (!value) return false;
|
||||
return value >= start && value <= end;
|
||||
};
|
||||
|
||||
type FetchCalendarDataParams = {
|
||||
userId: string;
|
||||
period: string;
|
||||
};
|
||||
|
||||
export const fetchCalendarData = async ({
|
||||
userId,
|
||||
period,
|
||||
}: FetchCalendarDataParams): Promise<CalendarData> => {
|
||||
const { year, month } = parsePeriod(period);
|
||||
const monthIndex = month - 1;
|
||||
const rangeStart = new Date(Date.UTC(year, monthIndex, 1));
|
||||
const rangeEnd = new Date(Date.UTC(year, monthIndex + 1, 0));
|
||||
const rangeStartKey = formatDateKey(rangeStart);
|
||||
const rangeEndKey = formatDateKey(rangeEnd);
|
||||
|
||||
const [lancamentoRows, cardRows, filterSources] = await Promise.all([
|
||||
db.query.lancamentos.findMany({
|
||||
where: and(
|
||||
eq(lancamentos.userId, userId),
|
||||
ne(lancamentos.transactionType, TRANSACTION_TYPE_TRANSFERENCIA),
|
||||
or(
|
||||
// Lançamentos cuja data de compra esteja no período do calendário
|
||||
and(
|
||||
gte(lancamentos.purchaseDate, rangeStart),
|
||||
lte(lancamentos.purchaseDate, rangeEnd),
|
||||
),
|
||||
// Boletos cuja data de vencimento esteja no período do calendário
|
||||
and(
|
||||
eq(lancamentos.paymentMethod, PAYMENT_METHOD_BOLETO),
|
||||
gte(lancamentos.dueDate, rangeStart),
|
||||
lte(lancamentos.dueDate, rangeEnd),
|
||||
),
|
||||
// Lançamentos de cartão do período (para calcular totais de vencimento)
|
||||
and(
|
||||
eq(lancamentos.period, period),
|
||||
ne(lancamentos.paymentMethod, PAYMENT_METHOD_BOLETO),
|
||||
),
|
||||
),
|
||||
),
|
||||
with: {
|
||||
pagador: true,
|
||||
conta: true,
|
||||
cartao: true,
|
||||
categoria: true,
|
||||
},
|
||||
}),
|
||||
db.query.cartoes.findMany({
|
||||
where: eq(cartoes.userId, userId),
|
||||
}),
|
||||
fetchLancamentoFilterSources(userId),
|
||||
]);
|
||||
|
||||
const lancamentosData = mapLancamentosData(lancamentoRows);
|
||||
const events: CalendarEvent[] = [];
|
||||
|
||||
const cardTotals = new Map<string, number>();
|
||||
for (const item of lancamentosData) {
|
||||
if (
|
||||
!item.cartaoId ||
|
||||
item.period !== period ||
|
||||
item.pagadorRole !== PAGADOR_ROLE_ADMIN
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const amount = Math.abs(item.amount ?? 0);
|
||||
cardTotals.set(
|
||||
item.cartaoId,
|
||||
(cardTotals.get(item.cartaoId) ?? 0) + amount,
|
||||
);
|
||||
}
|
||||
|
||||
for (const item of lancamentosData) {
|
||||
const isBoleto = item.paymentMethod === PAYMENT_METHOD_BOLETO;
|
||||
const isAdminPagador = item.pagadorRole === PAGADOR_ROLE_ADMIN;
|
||||
|
||||
// Para boletos, exibir apenas na data de vencimento e apenas se for pagador admin
|
||||
if (isBoleto) {
|
||||
if (
|
||||
isAdminPagador &&
|
||||
item.dueDate &&
|
||||
isWithinRange(item.dueDate, rangeStartKey, rangeEndKey)
|
||||
) {
|
||||
events.push({
|
||||
id: `${item.id}:boleto`,
|
||||
type: "boleto",
|
||||
date: item.dueDate,
|
||||
lancamento: item,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// Para outros tipos de lançamento, exibir na data de compra
|
||||
if (!isAdminPagador) {
|
||||
continue;
|
||||
}
|
||||
const purchaseDateKey = item.purchaseDate.slice(0, 10);
|
||||
if (isWithinRange(purchaseDateKey, rangeStartKey, rangeEndKey)) {
|
||||
events.push({
|
||||
id: item.id,
|
||||
type: "lancamento",
|
||||
date: purchaseDateKey,
|
||||
lancamento: item,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Exibir vencimentos apenas de cartões com lançamentos do pagador admin
|
||||
for (const card of cardRows) {
|
||||
if (!cardTotals.has(card.id)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const dueDayNumber = Number.parseInt(card.dueDay ?? "", 10);
|
||||
if (Number.isNaN(dueDayNumber)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const normalizedDay = clampDayInMonth(year, monthIndex, dueDayNumber);
|
||||
const dueDateKey = formatDateKey(
|
||||
new Date(Date.UTC(year, monthIndex, normalizedDay)),
|
||||
);
|
||||
|
||||
events.push({
|
||||
id: `${card.id}:cartao`,
|
||||
type: "cartao",
|
||||
date: dueDateKey,
|
||||
card: {
|
||||
id: card.id,
|
||||
name: card.name,
|
||||
dueDay: card.dueDay,
|
||||
closingDay: card.closingDay,
|
||||
brand: card.brand ?? null,
|
||||
status: card.status,
|
||||
logo: card.logo ?? null,
|
||||
totalDue: cardTotals.get(card.id) ?? null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const typePriority: Record<CalendarEvent["type"], number> = {
|
||||
lancamento: 0,
|
||||
boleto: 1,
|
||||
cartao: 2,
|
||||
};
|
||||
|
||||
events.sort((a, b) => {
|
||||
if (a.date === b.date) {
|
||||
return typePriority[a.type] - typePriority[b.type];
|
||||
}
|
||||
return a.date.localeCompare(b.date);
|
||||
});
|
||||
|
||||
const sluggedFilters = buildSluggedFilters(filterSources);
|
||||
const optionSets = buildOptionSets({
|
||||
...sluggedFilters,
|
||||
pagadorRows: filterSources.pagadorRows,
|
||||
});
|
||||
|
||||
const estabelecimentos = await fetchRecentEstablishments(userId);
|
||||
|
||||
return {
|
||||
events,
|
||||
formOptions: {
|
||||
pagadorOptions: optionSets.pagadorOptions,
|
||||
splitPagadorOptions: optionSets.splitPagadorOptions,
|
||||
defaultPagadorId: optionSets.defaultPagadorId,
|
||||
contaOptions: optionSets.contaOptions,
|
||||
cartaoOptions: optionSets.cartaoOptions,
|
||||
categoriaOptions: optionSets.categoriaOptions,
|
||||
estabelecimentos,
|
||||
},
|
||||
};
|
||||
};
|
||||
Reference in New Issue
Block a user