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:
@@ -0,0 +1,821 @@
|
||||
"use client";
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { ChevronDown, Loader2, Plus, Split, Trash2, Wand2 } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Controller, useFieldArray, useForm, useWatch, type Resolver } from "react-hook-form";
|
||||
import { toast } from "sonner";
|
||||
import { IconBadge } from "@/components/appearance/swatch";
|
||||
import { MoneyInput } from "@/components/money-input";
|
||||
import { ResponsiveDialog } from "@/components/responsive-dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
|
||||
import { Field, FieldDescription, FieldError, 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 { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { tr } from "@/i18n/tr";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { todayIstanbul } from "@/shared/dates";
|
||||
import { formatMoney } from "@/shared/format";
|
||||
import { formatMoneyInput, parseMoney } from "@/shared/money";
|
||||
import { transactionFormSchema, type TransactionForm } from "@/shared/schemas/transaction";
|
||||
import { MAX_SPLITS, TRANSACTION_TYPES, type TransactionType } from "@/shared/transactions";
|
||||
import {
|
||||
createTransactionAction,
|
||||
getTransactionFormOptionsAction,
|
||||
searchPayeesAction,
|
||||
updateTransactionAction,
|
||||
} from "../actions";
|
||||
import type { PayeeSuggestion, TransactionDetail, TransactionFormOptions } from "../service";
|
||||
|
||||
const t = tr.transactions;
|
||||
const f = t.fields;
|
||||
|
||||
export type TransactionFormMode =
|
||||
| { kind: "create"; type: TransactionType }
|
||||
| { kind: "edit"; transaction: TransactionDetail }
|
||||
| { kind: "copy"; transaction: TransactionDetail };
|
||||
|
||||
type SplitValue = { categoryId: string; amount: string; note: string };
|
||||
type FormValues = {
|
||||
type: TransactionType;
|
||||
amount: string;
|
||||
date: string;
|
||||
accountId: string;
|
||||
toAccountId: string;
|
||||
categoryId: string;
|
||||
splits: SplitValue[];
|
||||
payee: string;
|
||||
description: string;
|
||||
tags: string;
|
||||
};
|
||||
|
||||
function toValues(mode: TransactionFormMode, options: TransactionFormOptions | null): FormValues {
|
||||
if (mode.kind === "create") {
|
||||
return {
|
||||
type: mode.type,
|
||||
amount: "",
|
||||
date: todayIstanbul(),
|
||||
accountId: options?.accounts[0]?.id ?? "",
|
||||
toAccountId: "",
|
||||
categoryId: "",
|
||||
splits: [],
|
||||
payee: "",
|
||||
description: "",
|
||||
tags: "",
|
||||
};
|
||||
}
|
||||
const x = mode.transaction;
|
||||
return {
|
||||
type: x.type,
|
||||
amount: formatMoneyInput(x.amountMinor),
|
||||
date: mode.kind === "copy" ? todayIstanbul() : x.date,
|
||||
accountId: x.account.id,
|
||||
toAccountId: x.toAccount?.id ?? "",
|
||||
categoryId: x.categoryId ?? "",
|
||||
splits: x.splits.map((s) => ({
|
||||
categoryId: s.categoryId,
|
||||
amount: formatMoneyInput(s.amountMinor),
|
||||
note: s.note,
|
||||
})),
|
||||
payee: x.payeeName,
|
||||
description: x.description,
|
||||
tags: x.tags.join(", "),
|
||||
};
|
||||
}
|
||||
|
||||
function AccountSelect({
|
||||
id,
|
||||
value,
|
||||
onChange,
|
||||
accounts,
|
||||
invalid,
|
||||
exclude,
|
||||
}: {
|
||||
id: string;
|
||||
value: string;
|
||||
onChange: (v: string) => void;
|
||||
accounts: {
|
||||
id: string;
|
||||
name: string;
|
||||
icon?: TransactionFormOptions["accounts"][number]["icon"];
|
||||
color?: TransactionFormOptions["accounts"][number]["color"];
|
||||
}[];
|
||||
invalid?: boolean;
|
||||
exclude?: string;
|
||||
}) {
|
||||
const current = accounts.find((a) => a.id === value);
|
||||
return (
|
||||
<Select value={value || undefined} onValueChange={onChange}>
|
||||
<SelectTrigger id={id} className="w-full" aria-invalid={invalid}>
|
||||
<SelectValue placeholder={f.selectAccount}>{current?.name}</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent className="max-h-72">
|
||||
{accounts
|
||||
.filter((a) => a.id !== exclude)
|
||||
.map((a) => (
|
||||
<SelectItem key={a.id} value={a.id}>
|
||||
{a.icon && a.color ? (
|
||||
<IconBadge
|
||||
icon={a.icon}
|
||||
color={a.color}
|
||||
size="sm"
|
||||
className="size-5 [&_svg]:size-3"
|
||||
/>
|
||||
) : null}
|
||||
{a.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
);
|
||||
}
|
||||
|
||||
function CategorySelect({
|
||||
id,
|
||||
value,
|
||||
onChange,
|
||||
options,
|
||||
appearance,
|
||||
invalid,
|
||||
className,
|
||||
}: {
|
||||
id: string;
|
||||
value: string;
|
||||
onChange: (v: string) => void;
|
||||
options: TransactionFormOptions["categories"];
|
||||
appearance: TransactionFormOptions["categoryAppearance"];
|
||||
invalid?: boolean;
|
||||
className?: string;
|
||||
}) {
|
||||
const current = options.find((o) => o.id === value);
|
||||
return (
|
||||
<Select value={value || undefined} onValueChange={onChange}>
|
||||
<SelectTrigger id={id} className={cn("w-full", className)} aria-invalid={invalid}>
|
||||
<SelectValue placeholder={f.selectCategory}>{current?.path}</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent className="max-h-80">
|
||||
{options.map((o) => {
|
||||
const look = appearance[o.id];
|
||||
return (
|
||||
<SelectItem key={o.id} value={o.id}>
|
||||
<span
|
||||
className="flex items-center gap-2"
|
||||
style={{ paddingInlineStart: `${o.depth * 1}rem` }}
|
||||
>
|
||||
{look ? (
|
||||
<IconBadge
|
||||
icon={look.icon}
|
||||
color={look.color}
|
||||
size="sm"
|
||||
className="size-5 [&_svg]:size-3"
|
||||
/>
|
||||
) : null}
|
||||
<span className={o.depth === 0 ? "font-medium" : undefined}>{o.label}</span>
|
||||
</span>
|
||||
</SelectItem>
|
||||
);
|
||||
})}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
);
|
||||
}
|
||||
|
||||
/** Satıcı alanı: yazdıkça öneri; seçilince son kullanılan kategori/hesap önerilir. */
|
||||
function PayeeInput({
|
||||
value,
|
||||
onChange,
|
||||
onPick,
|
||||
}: {
|
||||
value: string;
|
||||
onChange: (v: string) => void;
|
||||
onPick: (p: PayeeSuggestion) => void;
|
||||
}) {
|
||||
const [items, setItems] = useState<PayeeSuggestion[]>([]);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [active, setActive] = useState(-1);
|
||||
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
function query(v: string) {
|
||||
if (timer.current) clearTimeout(timer.current);
|
||||
timer.current = setTimeout(async () => {
|
||||
const res = await searchPayeesAction(v);
|
||||
setItems(
|
||||
res.filter(
|
||||
(p) =>
|
||||
p.name.toLocaleLowerCase("tr-TR") !== v.trim().toLocaleLowerCase("tr-TR") ||
|
||||
res.length > 1,
|
||||
),
|
||||
);
|
||||
setActive(-1);
|
||||
}, 150);
|
||||
}
|
||||
|
||||
function pick(p: PayeeSuggestion) {
|
||||
onChange(p.name);
|
||||
onPick(p);
|
||||
setOpen(false);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
<Input
|
||||
id="tx-payee"
|
||||
value={value}
|
||||
placeholder={f.payeePlaceholder}
|
||||
autoComplete="off"
|
||||
role="combobox"
|
||||
aria-expanded={open && items.length > 0}
|
||||
aria-controls="tx-payee-list"
|
||||
aria-autocomplete="list"
|
||||
onChange={(e) => {
|
||||
onChange(e.target.value);
|
||||
setOpen(true);
|
||||
query(e.target.value);
|
||||
}}
|
||||
onFocus={() => {
|
||||
setOpen(true);
|
||||
query(value);
|
||||
}}
|
||||
onBlur={() => setTimeout(() => setOpen(false), 150)}
|
||||
onKeyDown={(e) => {
|
||||
if (!open || !items.length) return;
|
||||
if (e.key === "ArrowDown") {
|
||||
e.preventDefault();
|
||||
setActive((i) => Math.min(i + 1, items.length - 1));
|
||||
} else if (e.key === "ArrowUp") {
|
||||
e.preventDefault();
|
||||
setActive((i) => Math.max(i - 1, 0));
|
||||
} else if (e.key === "Enter" && active >= 0) {
|
||||
e.preventDefault();
|
||||
pick(items[active]!);
|
||||
} else if (e.key === "Escape") setOpen(false);
|
||||
}}
|
||||
/>
|
||||
{open && items.length > 0 ? (
|
||||
<ul
|
||||
id="tx-payee-list"
|
||||
role="listbox"
|
||||
className="absolute z-50 mt-1 max-h-56 w-full overflow-y-auto rounded-lg border bg-popover p-1 text-popover-foreground shadow-md"
|
||||
>
|
||||
{items.map((p, i) => (
|
||||
<li
|
||||
key={p.name}
|
||||
role="option"
|
||||
aria-selected={i === active}
|
||||
onMouseDown={(e) => {
|
||||
e.preventDefault();
|
||||
pick(p);
|
||||
}}
|
||||
className="cursor-pointer rounded-md px-2 py-1.5 text-sm hover:bg-accent aria-selected:bg-accent"
|
||||
>
|
||||
{p.name}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function TransactionFormDialog({
|
||||
mode,
|
||||
onOpenChange,
|
||||
}: {
|
||||
mode: TransactionFormMode | null;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}) {
|
||||
const [options, setOptions] = useState<TransactionFormOptions | null>(null);
|
||||
const [loadError, setLoadError] = useState<string | null>(null);
|
||||
const [advancedOpen, setAdvancedOpen] = useState(false);
|
||||
const [suggested, setSuggested] = useState(false);
|
||||
const form = useForm<FormValues, unknown, TransactionForm>({
|
||||
// FormValues, şemanın giriş şekliyle birebir (tutarlar string; zod kuruşa çevirir).
|
||||
resolver: zodResolver(transactionFormSchema) as unknown as Resolver<
|
||||
FormValues,
|
||||
unknown,
|
||||
TransactionForm
|
||||
>,
|
||||
defaultValues: toValues({ kind: "create", type: "expense" }, null),
|
||||
});
|
||||
const splits = useFieldArray({ control: form.control, name: "splits" });
|
||||
|
||||
// Form her açıldığında seçenekleri sunucudan al (hesaplar/kategoriler güncel olsun).
|
||||
useEffect(() => {
|
||||
if (!mode) return;
|
||||
let cancelled = false;
|
||||
getTransactionFormOptionsAction().then((res) => {
|
||||
if (cancelled) return;
|
||||
if (!res.ok) {
|
||||
setLoadError(res.error);
|
||||
return;
|
||||
}
|
||||
setLoadError(null);
|
||||
setOptions(res.data);
|
||||
form.reset(toValues(mode, res.data));
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [mode, form]);
|
||||
|
||||
const type = useWatch({ control: form.control, name: "type" });
|
||||
const amount = useWatch({ control: form.control, name: "amount" });
|
||||
const accountId = useWatch({ control: form.control, name: "accountId" });
|
||||
const splitValues = useWatch({ control: form.control, name: "splits" });
|
||||
const splitMode = splits.fields.length > 0;
|
||||
|
||||
// Düzenlemede arşivli/kapalı hesap veya kategori seçenek listesinde yoksa ekle (kaybolmasın).
|
||||
const accounts = useMemo(() => {
|
||||
const list = [...(options?.accounts ?? [])];
|
||||
if (mode && mode.kind !== "create") {
|
||||
for (const a of [mode.transaction.account, mode.transaction.toAccount]) {
|
||||
if (a && !list.some((x) => x.id === a.id))
|
||||
list.push({ ...a, type: "bank", icon: "wallet", color: "slate" });
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}, [options, mode]);
|
||||
const categories = useMemo(() => {
|
||||
const kind = type === "income" ? "income" : "expense";
|
||||
const list = (options?.categories ?? []).filter((c) => c.kind === kind);
|
||||
if (mode && mode.kind !== "create") {
|
||||
const extra = [
|
||||
...(mode.transaction.category
|
||||
? [{ id: mode.transaction.category.id, path: mode.transaction.category.path }]
|
||||
: []),
|
||||
...mode.transaction.splits.map((s) => ({ id: s.categoryId, path: s.path })),
|
||||
];
|
||||
for (const c of extra) {
|
||||
if (!list.some((x) => x.id === c.id))
|
||||
list.push({ id: c.id, label: c.path, path: c.path, depth: 0, kind });
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}, [options, type, mode]);
|
||||
|
||||
const totalMinor = parseMoney(amount ?? "") ?? 0;
|
||||
const splitSum = (splitValues ?? []).reduce((a, s) => a + (parseMoney(s.amount ?? "") ?? 0), 0);
|
||||
const remaining = totalMinor - splitSum;
|
||||
|
||||
function handleOpenChange(open: boolean) {
|
||||
if (!open) {
|
||||
setAdvancedOpen(false);
|
||||
setSuggested(false);
|
||||
}
|
||||
onOpenChange(open);
|
||||
}
|
||||
|
||||
function changeType(next: TransactionType) {
|
||||
form.setValue("type", next);
|
||||
// Kategoriler türe bağlıdır; tür değişince temizlenir.
|
||||
form.setValue("categoryId", "");
|
||||
splits.replace([]);
|
||||
if (next !== "transfer") form.setValue("toAccountId", "");
|
||||
form.clearErrors();
|
||||
}
|
||||
|
||||
function toggleSplit() {
|
||||
if (splitMode) {
|
||||
splits.replace([]);
|
||||
return;
|
||||
}
|
||||
const first = form.getValues("categoryId");
|
||||
splits.replace([
|
||||
{ categoryId: first, amount: form.getValues("amount"), note: "" },
|
||||
{ categoryId: "", amount: "", note: "" },
|
||||
]);
|
||||
form.setValue("categoryId", "");
|
||||
setAdvancedOpen(true);
|
||||
}
|
||||
|
||||
function fillRemaining() {
|
||||
const last = splits.fields.length - 1;
|
||||
if (last < 0) return;
|
||||
const current = parseMoney(form.getValues(`splits.${last}.amount`) ?? "") ?? 0;
|
||||
const next = current + remaining;
|
||||
if (next > 0)
|
||||
form.setValue(`splits.${last}.amount`, formatMoneyInput(next), { shouldValidate: true });
|
||||
}
|
||||
|
||||
function onPayeePicked(p: PayeeSuggestion) {
|
||||
let changed = false;
|
||||
// Kullanıcı seçimini ezme: yalnızca boş alanları doldur.
|
||||
if (p.lastAccountId && !form.getValues("accountId")) {
|
||||
form.setValue("accountId", p.lastAccountId);
|
||||
changed = true;
|
||||
} else if (p.lastAccountId && form.formState.dirtyFields.accountId === undefined) {
|
||||
form.setValue("accountId", p.lastAccountId);
|
||||
changed = true;
|
||||
}
|
||||
if (
|
||||
p.lastCategoryId &&
|
||||
!splitMode &&
|
||||
!form.getValues("categoryId") &&
|
||||
p.lastType === form.getValues("type")
|
||||
) {
|
||||
form.setValue("categoryId", p.lastCategoryId);
|
||||
changed = true;
|
||||
}
|
||||
setSuggested(changed);
|
||||
}
|
||||
|
||||
async function onSubmit() {
|
||||
if (!mode) return;
|
||||
const values = form.getValues();
|
||||
const payload = {
|
||||
...values,
|
||||
toAccountId: values.type === "transfer" ? values.toAccountId : "",
|
||||
categoryId: values.type === "transfer" || values.splits.length ? "" : values.categoryId,
|
||||
splits: values.type === "transfer" ? [] : values.splits,
|
||||
};
|
||||
const result =
|
||||
mode.kind === "edit"
|
||||
? await updateTransactionAction(mode.transaction.id, payload)
|
||||
: await createTransactionAction(payload);
|
||||
if (result.ok) {
|
||||
toast.success(mode.kind === "edit" ? t.toast.updated : t.toast.created);
|
||||
handleOpenChange(false);
|
||||
return;
|
||||
}
|
||||
for (const [name, message] of Object.entries(result.fieldErrors ?? {})) {
|
||||
if (!message) continue;
|
||||
form.setError(name as keyof FormValues, { message });
|
||||
if (name.startsWith("splits") || name === "tags") setAdvancedOpen(true);
|
||||
}
|
||||
if (!result.fieldErrors) form.setError("root", { message: result.error });
|
||||
}
|
||||
|
||||
const title =
|
||||
mode?.kind === "edit"
|
||||
? t.editTitle
|
||||
: mode?.kind === "copy"
|
||||
? t.copyTitle
|
||||
: t.createTitle[mode?.type ?? "expense"];
|
||||
const loading = Boolean(mode) && !options && !loadError;
|
||||
const noAccounts = options && options.accounts.length === 0;
|
||||
const errors = form.formState.errors;
|
||||
|
||||
return (
|
||||
<ResponsiveDialog
|
||||
open={Boolean(mode)}
|
||||
onOpenChange={handleOpenChange}
|
||||
title={title}
|
||||
footer={
|
||||
noAccounts || loadError ? null : (
|
||||
<>
|
||||
<Button variant="outline" type="button" onClick={() => handleOpenChange(false)}>
|
||||
{tr.common.cancel}
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
form="transaction-form"
|
||||
disabled={form.formState.isSubmitting || loading}
|
||||
>
|
||||
{form.formState.isSubmitting ? <Loader2 className="animate-spin" /> : null}
|
||||
{tr.common.save}
|
||||
</Button>
|
||||
</>
|
||||
)
|
||||
}
|
||||
>
|
||||
{loadError ? (
|
||||
<p className="text-sm text-destructive">{loadError}</p>
|
||||
) : loading ? (
|
||||
<div className="flex flex-col gap-4" role="status" aria-label={tr.common.loading}>
|
||||
<Skeleton className="h-9 w-full" />
|
||||
<Skeleton className="h-12 w-full" />
|
||||
<Skeleton className="h-9 w-full" />
|
||||
<Skeleton className="h-9 w-full" />
|
||||
</div>
|
||||
) : noAccounts ? (
|
||||
<div className="flex flex-col items-start gap-3 text-sm">
|
||||
<p className="text-muted-foreground">{t.noAccounts}</p>
|
||||
<Button asChild size="sm" onClick={() => handleOpenChange(false)}>
|
||||
<Link href="/hesaplar">{t.noAccountsLink}</Link>
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<form id="transaction-form" onSubmit={form.handleSubmit(onSubmit)} noValidate>
|
||||
<FieldGroup>
|
||||
{mode?.kind !== "edit" ? (
|
||||
<Tabs value={type} onValueChange={(v) => changeType(v as TransactionType)}>
|
||||
<TabsList className="w-full">
|
||||
{TRANSACTION_TYPES.map((x) => (
|
||||
<TabsTrigger key={x} value={x} className="flex-1">
|
||||
{t.types[x]}
|
||||
</TabsTrigger>
|
||||
))}
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
) : null}
|
||||
|
||||
<div className="grid gap-4 sm:grid-cols-[1fr_auto]">
|
||||
<Controller
|
||||
name="amount"
|
||||
control={form.control}
|
||||
render={({ field, fieldState }) => (
|
||||
<Field data-invalid={fieldState.invalid}>
|
||||
<FieldLabel htmlFor="tx-amount">{f.amount}</FieldLabel>
|
||||
<MoneyInput
|
||||
id="tx-amount"
|
||||
name={field.name}
|
||||
value={field.value}
|
||||
onChange={field.onChange}
|
||||
onBlur={field.onBlur}
|
||||
placeholder="0,00"
|
||||
className="h-11 text-lg"
|
||||
autoFocus={mode?.kind === "create"}
|
||||
aria-invalid={fieldState.invalid}
|
||||
/>
|
||||
{fieldState.invalid ? <FieldError errors={[fieldState.error]} /> : null}
|
||||
</Field>
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
name="date"
|
||||
control={form.control}
|
||||
render={({ field, fieldState }) => (
|
||||
<Field data-invalid={fieldState.invalid}>
|
||||
<FieldLabel htmlFor="tx-date">{f.date}</FieldLabel>
|
||||
<Input
|
||||
{...field}
|
||||
id="tx-date"
|
||||
type="date"
|
||||
className="h-11"
|
||||
aria-invalid={fieldState.invalid}
|
||||
/>
|
||||
{fieldState.invalid ? <FieldError errors={[fieldState.error]} /> : null}
|
||||
</Field>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className={cn("grid gap-4", type === "transfer" && "sm:grid-cols-2")}>
|
||||
<Controller
|
||||
name="accountId"
|
||||
control={form.control}
|
||||
render={({ field, fieldState }) => (
|
||||
<Field data-invalid={fieldState.invalid}>
|
||||
<FieldLabel htmlFor="tx-account">
|
||||
{type === "transfer" ? f.fromAccount : f.account}
|
||||
</FieldLabel>
|
||||
<AccountSelect
|
||||
id="tx-account"
|
||||
value={field.value}
|
||||
onChange={field.onChange}
|
||||
accounts={accounts}
|
||||
invalid={fieldState.invalid}
|
||||
/>
|
||||
{fieldState.invalid ? <FieldError errors={[fieldState.error]} /> : null}
|
||||
</Field>
|
||||
)}
|
||||
/>
|
||||
{type === "transfer" ? (
|
||||
<Controller
|
||||
name="toAccountId"
|
||||
control={form.control}
|
||||
render={({ field, fieldState }) => (
|
||||
<Field data-invalid={fieldState.invalid}>
|
||||
<FieldLabel htmlFor="tx-to-account">{f.toAccount}</FieldLabel>
|
||||
<AccountSelect
|
||||
id="tx-to-account"
|
||||
value={field.value}
|
||||
onChange={field.onChange}
|
||||
accounts={accounts}
|
||||
exclude={accountId}
|
||||
invalid={fieldState.invalid}
|
||||
/>
|
||||
{fieldState.invalid ? <FieldError errors={[fieldState.error]} /> : null}
|
||||
</Field>
|
||||
)}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{type !== "transfer" && !splitMode ? (
|
||||
<Controller
|
||||
name="categoryId"
|
||||
control={form.control}
|
||||
render={({ field, fieldState }) => (
|
||||
<Field data-invalid={fieldState.invalid}>
|
||||
<FieldLabel htmlFor="tx-category">{f.category}</FieldLabel>
|
||||
<div className="flex gap-2">
|
||||
<CategorySelect
|
||||
id="tx-category"
|
||||
value={field.value}
|
||||
onChange={field.onChange}
|
||||
options={categories}
|
||||
appearance={options?.categoryAppearance ?? {}}
|
||||
invalid={fieldState.invalid}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={toggleSplit}
|
||||
title={f.split}
|
||||
aria-label={f.split}
|
||||
>
|
||||
<Split />
|
||||
</Button>
|
||||
</div>
|
||||
{fieldState.invalid ? <FieldError errors={[fieldState.error]} /> : null}
|
||||
</Field>
|
||||
)}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<Controller
|
||||
name="payee"
|
||||
control={form.control}
|
||||
render={({ field }) => (
|
||||
<Field>
|
||||
<FieldLabel htmlFor="tx-payee">{f.payee}</FieldLabel>
|
||||
<PayeeInput
|
||||
value={field.value}
|
||||
onChange={field.onChange}
|
||||
onPick={onPayeePicked}
|
||||
/>
|
||||
{suggested ? <FieldDescription>{f.suggested}</FieldDescription> : null}
|
||||
</Field>
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
name="description"
|
||||
control={form.control}
|
||||
render={({ field, fieldState }) => (
|
||||
<Field data-invalid={fieldState.invalid}>
|
||||
<FieldLabel htmlFor="tx-description">{f.description}</FieldLabel>
|
||||
<Input {...field} id="tx-description" aria-invalid={fieldState.invalid} />
|
||||
{fieldState.invalid ? <FieldError errors={[fieldState.error]} /> : null}
|
||||
</Field>
|
||||
)}
|
||||
/>
|
||||
|
||||
<Collapsible open={advancedOpen} onOpenChange={setAdvancedOpen}>
|
||||
<CollapsibleTrigger asChild>
|
||||
<Button type="button" variant="ghost" className="-ml-2 w-fit">
|
||||
<ChevronDown
|
||||
className={cn("transition-transform", advancedOpen && "rotate-180")}
|
||||
/>
|
||||
{f.advanced}
|
||||
{splitMode ? (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
· {t.list.split(splits.fields.length)}
|
||||
</span>
|
||||
) : null}
|
||||
</Button>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent className="pt-3">
|
||||
<FieldGroup>
|
||||
<Controller
|
||||
name="tags"
|
||||
control={form.control}
|
||||
render={({ field, fieldState }) => (
|
||||
<Field data-invalid={fieldState.invalid}>
|
||||
<FieldLabel htmlFor="tx-tags">{f.tags}</FieldLabel>
|
||||
<Input {...field} id="tx-tags" aria-describedby="tx-tags-hint" />
|
||||
<FieldDescription id="tx-tags-hint">{f.tagsHint}</FieldDescription>
|
||||
</Field>
|
||||
)}
|
||||
/>
|
||||
|
||||
{type !== "transfer" ? (
|
||||
<div className="flex flex-col gap-3 rounded-xl border p-3">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<div>
|
||||
<p className="text-sm font-medium">{f.split}</p>
|
||||
<p className="text-xs text-muted-foreground">{f.splitHint}</p>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant={splitMode ? "outline" : "secondary"}
|
||||
size="sm"
|
||||
onClick={toggleSplit}
|
||||
>
|
||||
<Split />
|
||||
{splitMode ? tr.common.cancel : f.split}
|
||||
</Button>
|
||||
</div>
|
||||
{splits.fields.map((row, i) => (
|
||||
<div
|
||||
key={row.id}
|
||||
className="grid grid-cols-[1fr_8rem_auto] items-start gap-2"
|
||||
>
|
||||
<Controller
|
||||
name={`splits.${i}.categoryId`}
|
||||
control={form.control}
|
||||
render={({ field, fieldState }) => (
|
||||
<div>
|
||||
<CategorySelect
|
||||
id={`tx-split-${i}-category`}
|
||||
value={field.value}
|
||||
onChange={field.onChange}
|
||||
options={categories}
|
||||
appearance={options?.categoryAppearance ?? {}}
|
||||
invalid={fieldState.invalid}
|
||||
/>
|
||||
{fieldState.invalid ? (
|
||||
<FieldError errors={[fieldState.error]} />
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
name={`splits.${i}.amount`}
|
||||
control={form.control}
|
||||
render={({ field, fieldState }) => (
|
||||
<MoneyInput
|
||||
id={`tx-split-${i}-amount`}
|
||||
aria-label={`${f.amount} ${i + 1}`}
|
||||
name={field.name}
|
||||
value={field.value}
|
||||
onChange={field.onChange}
|
||||
onBlur={field.onBlur}
|
||||
placeholder="0,00"
|
||||
aria-invalid={fieldState.invalid}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => splits.remove(i)}
|
||||
disabled={splits.fields.length <= 2}
|
||||
aria-label={f.removeSplit}
|
||||
>
|
||||
<Trash2 />
|
||||
</Button>
|
||||
<Controller
|
||||
name={`splits.${i}.note`}
|
||||
control={form.control}
|
||||
render={({ field }) => (
|
||||
<Input
|
||||
{...field}
|
||||
placeholder={f.splitNote}
|
||||
aria-label={`${f.splitNote} ${i + 1}`}
|
||||
className="col-span-2 h-8 text-sm"
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
{splitMode ? (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => splits.append({ categoryId: "", amount: "", note: "" })}
|
||||
disabled={splits.fields.length >= MAX_SPLITS}
|
||||
>
|
||||
<Plus />
|
||||
{f.addSplit}
|
||||
</Button>
|
||||
<span
|
||||
role="status"
|
||||
className={cn(
|
||||
"ml-auto text-sm tabular-nums",
|
||||
remaining === 0 ? "text-income" : "text-expense",
|
||||
)}
|
||||
>
|
||||
{remaining === 0
|
||||
? f.remainingOk
|
||||
: `${f.remaining}: ${formatMoney(remaining)}`}
|
||||
</span>
|
||||
{remaining !== 0 ? (
|
||||
<Button type="button" variant="ghost" size="sm" onClick={fillRemaining}>
|
||||
<Wand2 />
|
||||
{f.fillRemaining}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
{errors.splits?.message || errors.splits?.root?.message ? (
|
||||
<FieldError>
|
||||
{errors.splits.message ?? errors.splits.root?.message}
|
||||
</FieldError>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</FieldGroup>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
{errors.root ? <FieldError>{errors.root.message}</FieldError> : null}
|
||||
</FieldGroup>
|
||||
</form>
|
||||
)}
|
||||
</ResponsiveDialog>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user