feat(transactions): işlem formu, bölme, liste, filtreler, ayrıntı ve CSV

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-05 03:23:30 +03:00
parent 1208e2d1eb
commit dcfa2f8c8d
8 changed files with 1761 additions and 75 deletions
@@ -0,0 +1,713 @@
"use client";
import {
ArrowLeftRight,
ChevronLeft,
ChevronRight,
Copy,
Download,
Filter,
Paperclip,
Pencil,
Plus,
Split,
Trash2,
X,
} from "lucide-react";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { useState, useTransition } from "react";
import { toast } from "sonner";
import { IconBadge } from "@/components/appearance/swatch";
import { useQuickAdd } from "@/components/layout/quick-add";
import { MoneyInput } from "@/components/money-input";
import { ResponsiveDialog } from "@/components/responsive-dialog";
import {
AlertDialog,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Field, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Skeleton } from "@/components/ui/skeleton";
import { tr } from "@/i18n/tr";
import { cn } from "@/lib/utils";
import { formatDate, formatDateTime, formatMoney } from "@/shared/format";
import type { TransactionFilters } from "@/shared/schemas/transaction";
import {
TRANSACTION_STATUSES,
TRANSACTION_TYPES,
type TransactionType,
} from "@/shared/transactions";
import { getTransactionAction, setTransactionDeletedAction } from "../actions";
import type {
TransactionDetail,
TransactionFormOptions,
TransactionListItem,
TransactionPage,
} from "../service";
const t = tr.transactions;
const ALL = "__all__";
const weekday = new Intl.DateTimeFormat("tr-TR", { weekday: "long", timeZone: "Europe/Istanbul" });
/** "2026-11-05" → "05.11.2026 · Perşembe" */
function dayLabel(ymd: string) {
const d = new Date(`${ymd}T12:00:00+03:00`);
return `${formatDate(d)} · ${weekday.format(d)}`;
}
function signed(type: TransactionType, amountMinor: number) {
return type === "income" ? amountMinor : type === "expense" ? -amountMinor : 0;
}
function Amount({
type,
amountMinor,
className,
}: {
type: TransactionType;
amountMinor: number;
className?: string;
}) {
const text =
type === "income"
? `+${formatMoney(amountMinor)}`
: type === "expense"
? `−${formatMoney(amountMinor)}`
: formatMoney(amountMinor);
return (
<span
className={cn(
"font-semibold whitespace-nowrap tabular-nums",
type === "income" && "text-income",
type === "expense" && "text-expense",
type === "transfer" && "text-muted-foreground",
className,
)}
>
{text}
</span>
);
}
function RowIcon({ item }: { item: TransactionListItem }) {
if (item.type === "transfer") {
return (
<span className="inline-flex size-9 shrink-0 items-center justify-center rounded-full bg-muted text-muted-foreground">
<ArrowLeftRight className="size-4.5" />
</span>
);
}
if (item.splitCount) {
return (
<span className="inline-flex size-9 shrink-0 items-center justify-center rounded-full bg-budget/15 text-budget">
<Split className="size-4.5" />
</span>
);
}
return item.category ? (
<IconBadge icon={item.category.icon} color={item.category.color} />
) : (
<IconBadge icon="tag" color="slate" />
);
}
function rowTitle(item: TransactionListItem) {
if (item.payeeName) return item.payeeName;
if (item.description) return item.description;
if (item.type === "transfer") return t.types.transfer;
return item.category?.name ?? t.types[item.type];
}
function rowSubtitle(item: TransactionListItem) {
if (item.type === "transfer")
return t.list.transfer(item.account.name, item.toAccount?.name ?? "—");
const what = item.splitCount ? t.list.split(item.splitCount) : (item.category?.path ?? "—");
return `${what} · ${item.account.name}`;
}
// --- Filtreler ---
type Options = TransactionFormOptions & { members: { id: string; name: string }[] };
function countActive(f: TransactionFilters) {
return (
[
"from",
"to",
"type",
"hesap",
"kategori",
"kisi",
"durum",
"min",
"max",
"etiket",
"q",
] as const
).filter((k) => f[k] !== undefined && f[k] !== "").length;
}
function FiltersDialog({
open,
onOpenChange,
filters,
raw,
options,
}: {
open: boolean;
onOpenChange: (o: boolean) => void;
filters: TransactionFilters;
raw: Record<string, string>;
options: Options;
}) {
const router = useRouter();
const pathname = usePathname();
const [v, setV] = useState<Record<string, string>>(raw);
const set = (k: string, value: string) => setV((prev) => ({ ...prev, [k]: value }));
const f = t.filters;
function apply(next: Record<string, string>) {
const params = new URLSearchParams();
for (const [k, value] of Object.entries(next)) if (value && k !== "sayfa") params.set(k, value);
router.push(params.size ? `${pathname}?${params}` : pathname);
onOpenChange(false);
}
const select = (key: string, label: string, items: { value: string; label: string }[]) => (
<Field>
<FieldLabel htmlFor={`flt-${key}`}>{label}</FieldLabel>
<Select value={v[key] || ALL} onValueChange={(x) => set(key, x === ALL ? "" : x)}>
<SelectTrigger id={`flt-${key}`} className="w-full">
<SelectValue>{items.find((i) => i.value === v[key])?.label ?? f.all}</SelectValue>
</SelectTrigger>
<SelectContent className="max-h-72">
<SelectItem value={ALL}>{f.all}</SelectItem>
{items.map((i) => (
<SelectItem key={i.value} value={i.value}>
{i.label}
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
);
return (
<ResponsiveDialog
open={open}
onOpenChange={(o) => {
if (o) setV(raw);
onOpenChange(o);
}}
title={f.title}
footer={
<>
<Button variant="outline" onClick={() => apply({})} disabled={!countActive(filters)}>
{f.clear}
</Button>
<Button onClick={() => apply(v)}>{f.apply}</Button>
</>
}
>
<form
onSubmit={(e) => {
e.preventDefault();
apply(v);
}}
>
<FieldGroup>
<Field>
<FieldLabel htmlFor="flt-q">{f.search}</FieldLabel>
<Input
id="flt-q"
value={v.q ?? ""}
onChange={(e) => set("q", e.target.value)}
placeholder={f.searchPlaceholder}
/>
</Field>
<div className="grid grid-cols-2 gap-3">
<Field>
<FieldLabel htmlFor="flt-from">{f.from}</FieldLabel>
<Input
id="flt-from"
type="date"
value={v.from ?? ""}
onChange={(e) => set("from", e.target.value)}
/>
</Field>
<Field>
<FieldLabel htmlFor="flt-to">{f.to}</FieldLabel>
<Input
id="flt-to"
type="date"
value={v.to ?? ""}
onChange={(e) => set("to", e.target.value)}
/>
</Field>
</div>
<div className="grid grid-cols-2 gap-3">
{select(
"type",
f.type,
TRANSACTION_TYPES.map((x) => ({ value: x, label: t.types[x] })),
)}
{select(
"durum",
f.status,
TRANSACTION_STATUSES.map((x) => ({ value: x, label: t.statuses[x] })),
)}
</div>
{select(
"hesap",
f.account,
options.accounts.map((a) => ({ value: a.id, label: a.name })),
)}
{select(
"kategori",
f.category,
options.categories.map((c) => ({
value: c.id,
label: `${c.kind === "income" ? "↑" : "↓"} ${c.path}`,
})),
)}
{select(
"kisi",
f.person,
options.members.map((m) => ({ value: m.id, label: m.name })),
)}
<div className="grid grid-cols-2 gap-3">
<Field>
<FieldLabel htmlFor="flt-min">{f.min}</FieldLabel>
<MoneyInput id="flt-min" value={v.min ?? ""} onChange={(x) => set("min", x)} />
</Field>
<Field>
<FieldLabel htmlFor="flt-max">{f.max}</FieldLabel>
<MoneyInput id="flt-max" value={v.max ?? ""} onChange={(x) => set("max", x)} />
</Field>
</div>
<Field>
<FieldLabel htmlFor="flt-tag">{f.tag}</FieldLabel>
<Input
id="flt-tag"
value={v.etiket ?? ""}
onChange={(e) => set("etiket", e.target.value)}
/>
</Field>
<button type="submit" hidden />
</FieldGroup>
</form>
</ResponsiveDialog>
);
}
// --- Ayrıntı ---
function DetailDialog({
detail,
loading,
canWrite,
onOpenChange,
onEdit,
onCopy,
onDelete,
}: {
detail: TransactionDetail | null;
loading: boolean;
canWrite: boolean;
onOpenChange: (o: boolean) => void;
onEdit: (d: TransactionDetail) => void;
onCopy: (d: TransactionDetail) => void;
onDelete: (d: TransactionDetail) => void;
}) {
const d = t.detail;
const row = (label: string, value: React.ReactNode) => (
<div className="flex items-start justify-between gap-4 py-2 text-sm">
<dt className="text-muted-foreground">{label}</dt>
<dd className="text-right">{value}</dd>
</div>
);
return (
<ResponsiveDialog
open={loading || Boolean(detail)}
onOpenChange={onOpenChange}
title={d.title}
footer={
detail && canWrite ? (
<>
<Button variant="destructive" onClick={() => onDelete(detail)}>
<Trash2 />
{t.actions.delete}
</Button>
<Button variant="outline" onClick={() => onCopy(detail)}>
<Copy />
{t.actions.copy}
</Button>
<Button onClick={() => onEdit(detail)}>
<Pencil />
{t.actions.edit}
</Button>
</>
) : null
}
>
{!detail ? (
<div className="flex flex-col gap-3" role="status" aria-label={tr.common.loading}>
<Skeleton className="h-10 w-1/2" />
<Skeleton className="h-32 w-full" />
</div>
) : (
<div className="flex flex-col gap-3">
<div className="flex items-center gap-3">
<RowIcon item={detail} />
<div className="min-w-0 flex-1">
<p className="truncate font-medium">{rowTitle(detail)}</p>
<p className="text-xs text-muted-foreground">{dayLabel(detail.date)}</p>
</div>
<Amount type={detail.type} amountMinor={detail.amountMinor} className="text-lg" />
</div>
<dl className="divide-y border-y">
{row(t.filters.type, <Badge variant="secondary">{t.types[detail.type]}</Badge>)}
{detail.status !== "posted" ? row(t.filters.status, t.statuses[detail.status]) : null}
{row(
detail.type === "transfer" ? t.fields.fromAccount : t.fields.account,
detail.account.name,
)}
{detail.toAccount ? row(t.fields.toAccount, detail.toAccount.name) : null}
{detail.category ? row(t.fields.category, detail.category.path) : null}
{detail.payeeName ? row(t.fields.payee, detail.payeeName) : null}
{detail.description ? row(t.fields.description, detail.description) : null}
{detail.tags.length
? row(
t.fields.tags,
<span className="flex flex-wrap justify-end gap-1">
{detail.tags.map((tag) => (
<Badge key={tag} variant="outline">
#{tag}
</Badge>
))}
</span>,
)
: null}
{row(d.createdBy, `${detail.createdBy.name} · ${formatDateTime(detail.createdAt)}`)}
{new Date(detail.updatedAt).getTime() - new Date(detail.createdAt).getTime() > 1000
? row(d.updatedBy, `${detail.updatedBy.name} · ${formatDateTime(detail.updatedAt)}`)
: null}
</dl>
{detail.splits.length ? (
<section aria-labelledby="tx-lines">
<h3 id="tx-lines" className="mb-1 text-sm font-medium">
{d.lines}
</h3>
<ul className="divide-y rounded-lg border">
{detail.splits.map((s, i) => (
<li key={i} className="flex items-center gap-3 p-2 text-sm">
<IconBadge icon={s.icon} color={s.color} size="sm" />
<span className="min-w-0 flex-1">
<span className="block truncate">{s.path}</span>
{s.note ? (
<span className="block truncate text-xs text-muted-foreground">
{s.note}
</span>
) : null}
</span>
<span className="tabular-nums">{formatMoney(s.amountMinor)}</span>
</li>
))}
</ul>
</section>
) : null}
</div>
)}
</ResponsiveDialog>
);
}
// --- Ana görünüm ---
export function TransactionsView({
data,
filters,
raw,
options,
canWrite,
}: {
data: TransactionPage;
filters: TransactionFilters;
raw: Record<string, string>;
options: Options;
canWrite: boolean;
}) {
const pathname = usePathname();
const { openQuickAdd, openTransactionForm } = useQuickAdd();
const [filtersOpen, setFiltersOpen] = useState(false);
const [detail, setDetail] = useState<TransactionDetail | null>(null);
const [detailLoading, setDetailLoading] = useState(false);
const [deleting, setDeleting] = useState<TransactionDetail | null>(null);
const [, startTransition] = useTransition();
const active = countActive(filters);
const pageHref = (page: number) => {
const params = new URLSearchParams(raw);
if (page > 1) params.set("sayfa", String(page));
else params.delete("sayfa");
return params.size ? `${pathname}?${params}` : pathname;
};
const exportHref = () => {
const params = new URLSearchParams(raw);
params.delete("sayfa");
return `/islemler/disa-aktar${params.size ? `?${params}` : ""}`;
};
async function openDetail(id: string) {
setDetailLoading(true);
setDetail(null);
const res = await getTransactionAction(id);
setDetailLoading(false);
if (res.ok) setDetail(res.data);
else toast.error(res.error);
}
function closeDetail() {
setDetail(null);
setDetailLoading(false);
}
function remove(d: TransactionDetail) {
setDeleting(null);
closeDetail();
startTransition(async () => {
const res = await setTransactionDeletedAction(d.id, true);
if (!res.ok) return void toast.error(res.error);
toast.success(t.toast.deleted, {
duration: 10_000,
action: {
label: t.actions.restore,
onClick: async () => {
const r = await setTransactionDeletedAction(d.id, false);
if (r.ok) toast.success(t.toast.restored);
else toast.error(r.error);
},
},
});
});
}
// Sayfadaki işlemleri güne göre grupla (liste zaten tarihe göre sıralı).
const groups: { date: string; items: TransactionListItem[] }[] = [];
for (const item of data.items) {
const last = groups.at(-1);
if (last?.date === item.date) last.items.push(item);
else groups.push({ date: item.date, items: [item] });
}
return (
<div className="flex flex-col gap-4">
<div className="flex flex-wrap items-center gap-2">
<Button variant="outline" onClick={() => setFiltersOpen(true)}>
<Filter />
{t.filters.open}
{active ? <Badge className="ml-1">{t.filters.active(active)}</Badge> : null}
</Button>
{active ? (
<Button variant="ghost" asChild>
<Link href={pathname}>
<X />
{t.filters.clear}
</Link>
</Button>
) : null}
<Button variant="ghost" asChild className="ml-auto">
{/* Dosya indirme: istemci gezinmesi değil, tam istek. */}
<a href={exportHref()} download>
<Download />
<span className="hidden sm:inline">{t.export}</span>
</a>
</Button>
{canWrite ? (
<Button onClick={() => openQuickAdd()}>
<Plus />
{t.new}
</Button>
) : null}
</div>
<div className="grid grid-cols-3 gap-3">
{(
[
["income", data.sums.incomeMinor, "text-income"],
["expense", data.sums.expenseMinor, "text-expense"],
["net", data.sums.incomeMinor - data.sums.expenseMinor, ""],
] as const
).map(([key, value, tone]) => (
<Card key={key} size="sm">
<CardHeader>
<CardDescription>{t.list.sums[key]}</CardDescription>
<CardTitle
className={cn(
"text-base tabular-nums sm:text-lg",
tone,
key === "net" && value < 0 && "text-expense",
)}
>
{formatMoney(value)}
</CardTitle>
</CardHeader>
</Card>
))}
</div>
{data.items.length === 0 ? (
<p className="rounded-xl border border-dashed p-8 text-center text-muted-foreground">
{active ? t.list.empty : t.list.emptyAll}
</p>
) : (
groups.map((g) => {
const net = g.items.reduce(
(a, i) => a + (i.status === "posted" ? signed(i.type, i.amountMinor) : 0),
0,
);
return (
<section key={g.date} aria-label={dayLabel(g.date)} className="flex flex-col gap-1.5">
<div className="flex items-center justify-between px-1 text-xs font-medium text-muted-foreground">
<h2 className="first-letter:uppercase">{dayLabel(g.date)}</h2>
<span
className={cn(
"tabular-nums",
net > 0 && "text-income",
net < 0 && "text-expense",
)}
title={t.list.dayTotal}
>
{net === 0 ? "" : `${net > 0 ? "+" : "−"}${formatMoney(Math.abs(net))}`}
</span>
</div>
<ul className="divide-y rounded-xl border bg-card">
{g.items.map((item) => (
<li key={item.id}>
<button
type="button"
onClick={() => openDetail(item.id)}
className="flex w-full items-center gap-3 p-3 text-left outline-none hover:bg-muted/50 focus-visible:bg-muted"
>
<RowIcon item={item} />
<span className="min-w-0 flex-1">
<span className="flex items-center gap-1.5">
<span className="truncate font-medium">{rowTitle(item)}</span>
{item.status !== "posted" ? (
<Badge variant="outline">{t.statuses[item.status]}</Badge>
) : null}
{item.attachmentCount ? (
<Paperclip className="size-3.5 shrink-0 text-muted-foreground" />
) : null}
</span>
<span className="block truncate text-xs text-muted-foreground">
{rowSubtitle(item)}
</span>
</span>
<Amount
type={item.type}
amountMinor={item.amountMinor}
className={cn(item.status !== "posted" && "opacity-60")}
/>
</button>
</li>
))}
</ul>
</section>
);
})
)}
{data.pageCount > 1 ? (
<nav
aria-label={tr.common.page(data.page, data.pageCount)}
className="flex items-center justify-between text-sm text-muted-foreground"
>
<span>{t.list.total(data.total)}</span>
<div className="flex items-center gap-2">
<span className="tabular-nums">{tr.common.page(data.page, data.pageCount)}</span>
<Button
variant="outline"
size="icon-sm"
asChild
disabled={data.page <= 1}
aria-label={tr.common.previous}
>
<Link
href={pageHref(data.page - 1)}
aria-disabled={data.page <= 1}
className={cn(data.page <= 1 && "pointer-events-none opacity-50")}
>
<ChevronLeft />
</Link>
</Button>
<Button variant="outline" size="icon-sm" asChild aria-label={tr.common.next}>
<Link
href={pageHref(data.page + 1)}
aria-disabled={data.page >= data.pageCount}
className={cn(data.page >= data.pageCount && "pointer-events-none opacity-50")}
>
<ChevronRight />
</Link>
</Button>
</div>
</nav>
) : data.total ? (
<p className="text-sm text-muted-foreground">{t.list.total(data.total)}</p>
) : null}
<FiltersDialog
open={filtersOpen}
onOpenChange={setFiltersOpen}
filters={filters}
raw={raw}
options={options}
/>
<DetailDialog
detail={detail}
loading={detailLoading}
canWrite={canWrite}
onOpenChange={(o) => !o && closeDetail()}
onEdit={(d) => {
closeDetail();
openTransactionForm({ kind: "edit", transaction: d });
}}
onCopy={(d) => {
closeDetail();
openTransactionForm({ kind: "copy", transaction: d });
}}
onDelete={setDeleting}
/>
<AlertDialog open={Boolean(deleting)} onOpenChange={(o) => !o && setDeleting(null)}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t.deleteTitle}</AlertDialogTitle>
<AlertDialogDescription>{t.deleteDescription}</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{tr.common.cancel}</AlertDialogCancel>
<Button variant="destructive" onClick={() => deleting && remove(deleting)}>
{t.actions.delete}
</Button>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}