feat(ui): ek ekleme alanı, carousel görüntüleyici, ekstre sayfası ve mutabakat penceresi

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-05 07:55:04 +03:00
parent 2e2e33233f
commit 8a9f5ddc7d
12 changed files with 1566 additions and 314 deletions
+31
View File
@@ -0,0 +1,31 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { hasHouseholdRole } from "@/features/households/roles";
import { StatementView } from "@/features/transactions/components/statement-view";
import { currentMonth, getAccountStatement } from "@/features/transactions/statement";
import { tr } from "@/i18n/tr";
import { requireActiveHousehold } from "@/lib/dal";
import { MONTH_PATTERN } from "@/shared/statement";
export const metadata: Metadata = { title: tr.statement.title };
/** /hesaplar/:id?ay=2026-11 — aylık hesap ekstresi (yürüyen bakiye) ve mutabakat. */
export default async function AccountStatementPage({
params,
searchParams,
}: PageProps<"/hesaplar/[id]">) {
const { user, household } = await requireActiveHousehold("viewer");
const [{ id }, sp] = await Promise.all([params, searchParams]);
const now = currentMonth();
const requested = typeof sp.ay === "string" && MONTH_PATTERN.test(sp.ay) ? sp.ay : now;
const month = requested > now ? now : requested;
const statement = await getAccountStatement(user.id, household.id, id, month);
if (!statement) notFound();
return (
<StatementView
key={`${id}-${month}`}
statement={statement}
canWrite={hasHouseholdRole(household.role, "member")}
/>
);
}
+1 -1
View File
@@ -27,7 +27,7 @@ export type NavItem = {
/** Şu an tamamlanmış en yüksek faz — sayfalar eklendikçe artar. */
/** Alt fazlar ondalıkla: 6.1 = Faz 6a. */
export const CURRENT_PHASE = 6.2;
export const CURRENT_PHASE = 6.3;
export const isAvailable = (item: NavItem) => item.phase <= CURRENT_PHASE;
+242
View File
@@ -0,0 +1,242 @@
"use client";
import * as React from "react";
import { cn } from "cn";
import useEmblaCarousel, { type UseEmblaCarouselType } from "embla-carousel-react";
import { Button } from "@/components/ui/button";
import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react";
type CarouselApi = UseEmblaCarouselType[1];
type UseCarouselParameters = Parameters<typeof useEmblaCarousel>;
type CarouselOptions = UseCarouselParameters[0];
type CarouselPlugin = UseCarouselParameters[1];
type CarouselProps = {
opts?: CarouselOptions;
plugins?: CarouselPlugin;
orientation?: "horizontal" | "vertical";
setApi?: (api: CarouselApi) => void;
};
type CarouselContextProps = {
carouselRef: ReturnType<typeof useEmblaCarousel>[0];
api: ReturnType<typeof useEmblaCarousel>[1];
scrollPrev: () => void;
scrollNext: () => void;
canScrollPrev: boolean;
canScrollNext: boolean;
} & CarouselProps;
const CarouselContext = React.createContext<CarouselContextProps | null>(null);
function useCarousel() {
const context = React.useContext(CarouselContext);
if (!context) {
throw new Error("useCarousel must be used within a <Carousel />");
}
return context;
}
function Carousel({
orientation = "horizontal",
opts,
setApi,
plugins,
className,
children,
...props
}: React.ComponentProps<"div"> & CarouselProps) {
const [carouselRef, api] = useEmblaCarousel(
{
...opts,
axis: orientation === "horizontal" ? "x" : "y",
},
plugins,
);
const [canScrollPrev, setCanScrollPrev] = React.useState(false);
const [canScrollNext, setCanScrollNext] = React.useState(false);
const onSelect = React.useCallback((api: CarouselApi) => {
if (!api) return;
setCanScrollPrev(api.canScrollPrev());
setCanScrollNext(api.canScrollNext());
}, []);
const scrollPrev = React.useCallback(() => {
api?.scrollPrev();
}, [api]);
const scrollNext = React.useCallback(() => {
api?.scrollNext();
}, [api]);
const handleKeyDown = React.useCallback(
(event: React.KeyboardEvent<HTMLDivElement>) => {
if (event.key === "ArrowLeft") {
event.preventDefault();
scrollPrev();
} else if (event.key === "ArrowRight") {
event.preventDefault();
scrollNext();
}
},
[scrollPrev, scrollNext],
);
React.useEffect(() => {
if (!api || !setApi) return;
setApi(api);
}, [api, setApi]);
React.useEffect(() => {
if (!api) return;
// İlk durum bir sonraki karede okunur (effect içinde senkron setState yapılmaz).
const frame = requestAnimationFrame(() => onSelect(api));
api.on("reInit", onSelect);
api.on("select", onSelect);
return () => {
cancelAnimationFrame(frame);
api.off("select", onSelect);
api.off("reInit", onSelect);
};
}, [api, onSelect]);
return (
<CarouselContext.Provider
value={{
carouselRef,
api: api,
opts,
orientation: orientation || (opts?.axis === "y" ? "vertical" : "horizontal"),
scrollPrev,
scrollNext,
canScrollPrev,
canScrollNext,
}}
>
<div
onKeyDownCapture={handleKeyDown}
className={cn("relative", className)}
role="region"
aria-roledescription="carousel"
data-slot="carousel"
{...props}
>
{children}
</div>
</CarouselContext.Provider>
);
}
function CarouselContent({
className,
containerClassName,
...props
}: React.ComponentProps<"div"> & { containerClassName?: string }) {
const { carouselRef, orientation } = useCarousel();
return (
<div
ref={carouselRef}
className={cn("overflow-hidden", containerClassName)}
data-slot="carousel-content"
>
<div
className={cn("flex", orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col", className)}
{...props}
/>
</div>
);
}
function CarouselItem({ className, ...props }: React.ComponentProps<"div">) {
const { orientation } = useCarousel();
return (
<div
role="group"
aria-roledescription="slide"
data-slot="carousel-item"
className={cn(
"min-w-0 shrink-0 grow-0 basis-full",
orientation === "horizontal" ? "pl-4" : "pt-4",
className,
)}
{...props}
/>
);
}
function CarouselPrevious({
className,
variant = "outline",
size = "icon-sm",
...props
}: React.ComponentProps<typeof Button>) {
const { orientation, scrollPrev, canScrollPrev } = useCarousel();
return (
<Button
data-slot="carousel-previous"
variant={variant}
size={size}
className={cn(
"absolute touch-manipulation rounded-full",
orientation === "horizontal"
? "inset-y-0 -left-12 my-auto"
: "-top-12 left-1/2 -translate-x-1/2 rotate-90",
className,
)}
disabled={!canScrollPrev}
onClick={scrollPrev}
{...props}
>
<ChevronLeftIcon />
<span className="sr-only">Previous slide</span>
</Button>
);
}
function CarouselNext({
className,
variant = "outline",
size = "icon-sm",
...props
}: React.ComponentProps<typeof Button>) {
const { orientation, scrollNext, canScrollNext } = useCarousel();
return (
<Button
data-slot="carousel-next"
variant={variant}
size={size}
className={cn(
"absolute touch-manipulation rounded-full",
orientation === "horizontal"
? "inset-y-0 -right-12 my-auto"
: "-bottom-12 left-1/2 -translate-x-1/2 rotate-90",
className,
)}
disabled={!canScrollNext}
onClick={scrollNext}
{...props}
>
<ChevronRightIcon />
<span className="sr-only">Next slide</span>
</Button>
);
}
export {
type CarouselApi,
Carousel,
CarouselContent,
CarouselItem,
CarouselPrevious,
CarouselNext,
useCarousel,
};
@@ -110,12 +110,14 @@ export function AccountsView({
<li className={cn("flex items-center gap-3 p-3", a.archived && "opacity-60")}>
<IconBadge icon={a.icon} color={a.color} />
<div className="min-w-0 flex-1">
<Link
href={`/islemler?hesap=${a.id}`}
className="block truncate font-medium hover:underline"
>
{a.name}
</Link>
{/* Gizli hesabın ekstresi yalnızca sahibine açılır. */}
{a.balanceMinor === null ? (
<span className="block truncate font-medium">{a.name}</span>
) : (
<Link href={`/hesaplar/${a.id}`} className="block truncate font-medium hover:underline">
{a.name}
</Link>
)}
<div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">
{a.type === "meal_card" && a.mealCardProvider ? (
<span>{t.providers[a.mealCardProvider]}</span>
@@ -0,0 +1,168 @@
"use client";
import { Loader2, Paperclip, X } from "lucide-react";
import { useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import { tr } from "@/i18n/tr";
import type { ActionResult } from "@/lib/action-result";
import { cn } from "@/lib/utils";
import {
acceptAttribute,
MAX_ATTACHMENTS_PER_RECORD,
type AttachmentKind,
} from "@/shared/attachments";
import type { AttachmentInfo } from "../service";
import { AttachmentThumb } from "./attachment-strip";
import { AttachmentViewer } from "./attachment-viewer";
const t = tr.attachments;
/** Tek dosyayı /api/files'a yükler. */
async function uploadFile(file: File): Promise<ActionResult<AttachmentInfo>> {
const body = new FormData();
body.append("file", file);
try {
const res = await fetch("/api/files", { method: "POST", body });
return (await res.json()) as ActionResult<AttachmentInfo>;
} catch {
return { ok: false, error: t.errors.upload };
}
}
/**
* Formdaki küçük "Ek ekle" alanı (Bölüm 6.3): seçilen dosyalar hemen yüklenir (bekleyen ek),
* küçük önizleme ve sayaç gösterilir; kayıt kaydedilince ekler kayda bağlanır.
*/
export function AttachmentPicker({
value,
onChange,
allowedKinds,
onBusyChange,
}: {
value: AttachmentInfo[];
onChange: (items: AttachmentInfo[]) => void;
allowedKinds: readonly AttachmentKind[];
onBusyChange?: (busy: boolean) => void;
}) {
const inputRef = useRef<HTMLInputElement>(null);
const [uploading, setUploading] = useState(0);
const [errors, setErrors] = useState<string[]>([]);
const [viewer, setViewer] = useState<number | null>(null);
const invalid = value.filter((a) => !allowedKinds.includes(a.kind));
const room = MAX_ATTACHMENTS_PER_RECORD - value.length;
async function onFiles(files: FileList | null) {
if (!files?.length) return;
const list = [...files];
const accepted = list.slice(0, Math.max(0, room));
const nextErrors: string[] = [];
if (list.length > accepted.length)
nextErrors.push(t.errors.tooMany(MAX_ATTACHMENTS_PER_RECORD));
setUploading(accepted.length);
onBusyChange?.(true);
let items = value;
for (const file of accepted) {
const result = await uploadFile(file);
if (result.ok) {
items = [...items, result.data];
onChange(items);
} else {
nextErrors.push(`${file.name}: ${result.error}`);
}
setUploading((n) => n - 1);
}
setErrors(nextErrors);
onBusyChange?.(false);
if (inputRef.current) inputRef.current.value = "";
}
function remove(id: string) {
onChange(value.filter((a) => a.id !== id));
}
return (
<div className="flex flex-col gap-2">
<div className="flex flex-wrap items-center gap-2">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => inputRef.current?.click()}
disabled={room <= 0 || uploading > 0}
>
{uploading > 0 ? <Loader2 className="animate-spin" /> : <Paperclip />}
{uploading > 0 ? t.uploading : t.add}
</Button>
<span className="text-xs text-muted-foreground">
{value.length
? t.count(value.length)
: allowedKinds.includes("pdf")
? t.addHint.imagePdf
: t.addHint.image}
</span>
<input
ref={inputRef}
type="file"
multiple
accept={acceptAttribute(allowedKinds)}
className="sr-only"
tabIndex={-1}
aria-label={t.add}
onChange={(e) => onFiles(e.target.files)}
/>
</div>
{value.length || uploading ? (
<ul className="flex flex-wrap gap-1.5">
{value.map((item, i) => (
<li key={item.id} className="relative">
<AttachmentThumb
item={item}
className={cn(
"size-10",
!allowedKinds.includes(item.kind) && "border-destructive ring-1 ring-destructive",
)}
onClick={() => setViewer(i)}
/>
<button
type="button"
onClick={() => remove(item.id)}
className="absolute -top-1.5 -right-1.5 flex size-5 items-center justify-center rounded-full border bg-background text-muted-foreground shadow-sm hover:text-foreground"
aria-label={`${t.remove}: ${item.name}`}
>
<X className="size-3" />
</button>
</li>
))}
{Array.from({ length: uploading }, (_, i) => (
<li
key={`up-${i}`}
className="flex size-10 items-center justify-center rounded-md border border-dashed"
aria-label={t.uploading}
>
<Loader2 className="size-4 animate-spin text-muted-foreground" />
</li>
))}
</ul>
) : null}
{invalid.length ? (
<p className="text-xs text-destructive" role="alert">
{t.errors.kindNotAllowed}
</p>
) : null}
{errors.map((e) => (
<p key={e} className="text-xs text-destructive" role="alert">
{e}
</p>
))}
<AttachmentViewer
items={value}
startIndex={viewer ?? 0}
open={viewer !== null}
onOpenChange={(open) => !open && setViewer(null)}
/>
</div>
);
}
@@ -0,0 +1,75 @@
"use client";
import { FileText, Paperclip } from "lucide-react";
import { useState } from "react";
import { tr } from "@/i18n/tr";
import type { AttachmentInfo } from "../service";
import { AttachmentViewer } from "./attachment-viewer";
const t = tr.attachments;
const VISIBLE = 4;
/** Ayrıntıda küçük önizleme şeridi (en fazla 4 + "+N"); tıklayınca görüntüleyici açılır. */
export function AttachmentStrip({ items }: { items: AttachmentInfo[] }) {
const [viewer, setViewer] = useState<number | null>(null);
if (!items.length) return null;
const shown = items.slice(0, VISIBLE);
const rest = items.length - shown.length;
return (
<div className="flex items-center gap-2">
<Paperclip className="size-4 shrink-0 text-muted-foreground" aria-hidden />
<span className="sr-only">{t.count(items.length)}</span>
<ul className="flex gap-1.5">
{shown.map((item, i) => (
<li key={item.id} className="relative">
<AttachmentThumb item={item} onClick={() => setViewer(i)} />
{rest > 0 && i === shown.length - 1 ? (
<button
type="button"
onClick={() => setViewer(i + 1)}
className="absolute inset-0 flex items-center justify-center rounded-md bg-black/55 text-sm font-medium text-white"
aria-label={`${t.viewerTitle}: ${t.moreCount(rest)}`}
>
{t.moreCount(rest)}
</button>
) : null}
</li>
))}
</ul>
<AttachmentViewer
items={items}
startIndex={viewer ?? 0}
open={viewer !== null}
onOpenChange={(open) => !open && setViewer(null)}
/>
</div>
);
}
export function AttachmentThumb({
item,
onClick,
className = "size-12",
}: {
item: AttachmentInfo;
onClick?: () => void;
className?: string;
}) {
return (
<button
type="button"
onClick={onClick}
title={item.name}
aria-label={item.name}
className={`${className} flex items-center justify-center overflow-hidden rounded-md border bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none`}
>
{item.thumbUrl ? (
// eslint-disable-next-line @next/next/no-img-element -- yetkili özel dosya
<img src={item.thumbUrl} alt="" className="size-full object-cover" loading="lazy" />
) : (
<FileText className="size-5 text-muted-foreground" aria-hidden />
)}
</button>
);
}
@@ -0,0 +1,170 @@
"use client";
import { Download, ExternalLink, FileText, Maximize, Minimize } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import {
Carousel,
CarouselContent,
CarouselItem,
CarouselNext,
CarouselPrevious,
type CarouselApi,
} from "@/components/ui/carousel";
import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog";
import { tr } from "@/i18n/tr";
import { formatFileSize } from "@/shared/attachments";
import type { AttachmentInfo } from "../service";
const t = tr.attachments;
/**
* Ek dosya görüntüleyici (Bölüm 6.3): carousel (oklar, kaydırma, klavye okları), tam ekran ve
* "2 / 5" göstergesi. PDF'ler ikon + "Aç" düğmesiyle gösterilir (tarayıcının PDF görüntüleyicisi).
*/
export function AttachmentViewer({
items,
startIndex,
open,
onOpenChange,
}: {
items: AttachmentInfo[];
startIndex: number;
open: boolean;
onOpenChange: (open: boolean) => void;
}) {
const [api, setApi] = useState<CarouselApi>();
const [index, setIndex] = useState(startIndex);
const [fullscreen, setFullscreen] = useState(false);
const containerRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!api) return;
const update = () => setIndex(api.selectedScrollSnap());
api.on("select", update);
api.on("reInit", update);
return () => {
api.off("select", update);
api.off("reInit", update);
};
}, [api]);
useEffect(() => {
const onChange = () => setFullscreen(document.fullscreenElement === containerRef.current);
document.addEventListener("fullscreenchange", onChange);
return () => document.removeEventListener("fullscreenchange", onChange);
}, []);
function handleOpenChange(next: boolean) {
if (!next && document.fullscreenElement) void document.exitFullscreen();
if (next) setIndex(startIndex);
onOpenChange(next);
}
async function toggleFullscreen() {
if (document.fullscreenElement) await document.exitFullscreen();
else await containerRef.current?.requestFullscreen().catch(() => {});
}
/** Odak carousel dışındayken de (ör. kapat düğmesi) ok tuşları çalışsın. */
function onKeyDown(event: React.KeyboardEvent) {
if (event.defaultPrevented) return;
if (event.key === "ArrowLeft") {
event.preventDefault();
api?.scrollPrev();
} else if (event.key === "ArrowRight") {
event.preventDefault();
api?.scrollNext();
}
}
const current = items[Math.min(index, items.length - 1)];
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent
className="flex h-[min(90dvh,900px)] w-[calc(100vw-1rem)] max-w-5xl flex-col gap-0 p-0 sm:max-w-5xl"
onKeyDown={onKeyDown}
>
<div ref={containerRef} className="flex min-h-0 flex-1 flex-col bg-background">
<div className="flex items-center gap-2 border-b px-3 py-2 pr-12">
<DialogTitle className="min-w-0 flex-1 truncate text-sm">
{current?.name ?? t.viewerTitle}
</DialogTitle>
<DialogDescription className="sr-only">{t.viewerTitle}</DialogDescription>
<span
className="shrink-0 text-xs text-muted-foreground tabular-nums"
aria-live="polite"
>
{t.position(index + 1, items.length)}
</span>
{current ? (
<Button asChild variant="ghost" size="icon-sm" aria-label={t.download}>
<a href={`${current.url}?indir=1`} download>
<Download />
</a>
</Button>
) : null}
<Button
variant="ghost"
size="icon-sm"
onClick={toggleFullscreen}
aria-label={fullscreen ? t.exitFullscreen : t.fullscreen}
>
{fullscreen ? <Minimize /> : <Maximize />}
</Button>
</div>
<Carousel
setApi={setApi}
opts={{ startIndex, loop: false }}
className="flex min-h-0 flex-1 flex-col"
aria-label={t.viewerTitle}
>
<CarouselContent className="h-full" containerClassName="h-full min-h-0 flex-1">
{items.map((item) => (
<CarouselItem
key={item.id}
className="flex h-full items-center justify-center p-4 pl-8"
>
{item.kind === "image" ? (
// eslint-disable-next-line @next/next/no-img-element -- yetkili özel dosya; optimizasyon hattına girmez
<img
src={item.url}
alt={item.name}
width={item.width ?? undefined}
height={item.height ?? undefined}
className="max-h-full max-w-full rounded-md object-contain"
draggable={false}
/>
) : (
<div className="flex flex-col items-center gap-3 text-center">
<FileText className="size-16 text-muted-foreground" aria-hidden />
<div>
<p className="font-medium break-all">{item.name}</p>
<p className="text-sm text-muted-foreground">
{t.pdf} · {formatFileSize(item.size)}
</p>
</div>
<Button asChild>
<a href={item.url} target="_blank" rel="noopener">
<ExternalLink />
{t.open}
</a>
</Button>
</div>
)}
</CarouselItem>
))}
</CarouselContent>
{items.length > 1 ? (
<>
<CarouselPrevious className="left-3" aria-label={t.previous} />
<CarouselNext className="right-3" aria-label={t.next} />
</>
) : null}
</Carousel>
</div>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,387 @@
"use client";
import {
ArrowLeft,
CheckCheck,
ChevronLeft,
ChevronRight,
List,
Loader2,
Scale,
} from "lucide-react";
import Link from "next/link";
import { useState } from "react";
import { toast } from "sonner";
import { MoneyInput } from "@/components/money-input";
import { PageHeader } from "@/components/page-header";
import { ResponsiveDialog } from "@/components/responsive-dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Field, FieldDescription, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { tr } from "@/i18n/tr";
import { cn } from "@/lib/utils";
import { todayIstanbul } from "@/shared/dates";
import { formatDate, formatMoney } from "@/shared/format";
import { previewReconciliationAction, reconcileAccountAction } from "../actions";
import type { AccountStatement, ReconcilePreview, StatementRow } from "../statement";
import { RowIcon, rowSubtitle, rowTitle, useTransactionDetail } from "./transaction-parts";
const t = tr.statement;
const r = t.reconcile;
const monthFmt = new Intl.DateTimeFormat("tr-TR", {
month: "long",
year: "numeric",
timeZone: "Europe/Istanbul",
});
const monthLabel = (ym: string) => monthFmt.format(new Date(`${ym}-15T12:00:00+03:00`));
const dateLabel = (ymd: string) => formatDate(new Date(`${ymd}T12:00:00+03:00`));
function SignedMoney({ minor, className }: { minor: number; className?: string }) {
return (
<span
className={cn(
"font-semibold whitespace-nowrap tabular-nums",
minor > 0 && "text-income",
minor < 0 && "text-expense",
className,
)}
>
{minor > 0 ? "+" : minor < 0 ? "−" : ""}
{formatMoney(Math.abs(minor))}
</span>
);
}
export function StatementView({
statement: s,
canWrite,
}: {
statement: AccountStatement;
canWrite: boolean;
}) {
const { openDetail, element: detailElement } = useTransactionDetail(canWrite);
const [reconcileOpen, setReconcileOpen] = useState(false);
const base = `/hesaplar/${s.account.id}`;
return (
<div className="flex flex-col gap-4">
<Button variant="ghost" size="sm" asChild className="-ml-2 w-fit">
<Link href="/hesaplar">
<ArrowLeft />
{t.back}
</Link>
</Button>
<PageHeader
title={s.account.name}
description={`${tr.accounts.types[s.account.type]} · ${t.current}: ${formatMoney(s.currentBalanceMinor)}`}
actions={
<>
<Button variant="outline" asChild>
<Link href={`/islemler?hesap=${s.account.id}`}>
<List />
<span className="hidden sm:inline">{t.allTransactions}</span>
</Link>
</Button>
{canWrite && s.canReconcile ? (
<Button onClick={() => setReconcileOpen(true)}>
<Scale />
{r.open}
</Button>
) : null}
</>
}
/>
<div className="flex items-center justify-between gap-2">
<Button variant="outline" size="icon-sm" asChild aria-label={t.prevMonth}>
<Link href={`${base}?ay=${s.prevMonth}`}>
<ChevronLeft />
</Link>
</Button>
<h2 className="text-base font-medium capitalize">{monthLabel(s.month)}</h2>
{s.nextMonth ? (
<Button variant="outline" size="icon-sm" asChild aria-label={t.nextMonth}>
<Link href={`${base}?ay=${s.nextMonth}`}>
<ChevronRight />
</Link>
</Button>
) : (
<Button variant="outline" size="icon-sm" disabled aria-label={t.nextMonth}>
<ChevronRight />
</Button>
)}
</div>
<div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
{(
[
[t.opening, s.openingMinor, false],
[t.inflow, s.inflowMinor, true],
[t.outflow, -s.outflowMinor, true],
[t.closing, s.closingMinor, false],
] as const
).map(([label, value, colored]) => (
<Card key={label} size="sm">
<CardHeader>
<CardDescription>{label}</CardDescription>
<CardTitle className="text-base">
{colored ? (
<SignedMoney minor={value} />
) : (
<span className="tabular-nums">{formatMoney(value)}</span>
)}
</CardTitle>
</CardHeader>
</Card>
))}
</div>
<p className="flex items-center gap-1.5 text-xs text-muted-foreground">
<CheckCheck className="size-3.5" aria-hidden />
{s.lastReconciliation
? t.lastReconciliation(
dateLabel(s.lastReconciliation.date),
formatMoney(s.lastReconciliation.statementBalanceMinor),
)
: t.noReconciliation}
</p>
{s.rows.length === 0 ? (
<Card>
<CardHeader>
<CardDescription>{t.empty}</CardDescription>
</CardHeader>
</Card>
) : (
<ul className="divide-y rounded-xl border bg-card">
{s.rows.map((row) => (
<li key={row.item.id}>
<StatementRowView row={row} onOpen={() => openDetail(row.item.id)} />
</li>
))}
</ul>
)}
{s.truncated ? <p className="text-xs text-muted-foreground">{t.truncated}</p> : null}
{detailElement}
<ReconcileDialog
open={reconcileOpen}
onOpenChange={setReconcileOpen}
accountId={s.account.id}
isLiability={s.account.isLiability}
/>
</div>
);
}
function StatementRowView({ row, onOpen }: { row: StatementRow; onOpen: () => void }) {
const content = (
<>
<RowIcon item={row.item} />
<span className="min-w-0 flex-1">
<span className="flex items-center gap-1.5">
<span className="truncate font-medium">{rowTitle(row.item)}</span>
{row.reconciled ? (
<CheckCheck className="size-3.5 shrink-0 text-income" aria-label={t.reconciledHint} />
) : null}
</span>
<span className="block truncate text-xs text-muted-foreground">
{dateLabel(row.item.date)} · {rowSubtitle(row.item)}
</span>
</span>
<span className="flex flex-col items-end">
<SignedMoney minor={row.deltaMinor} />
<span className="text-xs text-muted-foreground tabular-nums" title={t.balanceAfter}>
{formatMoney(row.balanceMinor)}
</span>
</span>
</>
);
const cls = "flex w-full items-center gap-3 p-3 text-left";
// Gizli karşı hesaba dokunan işlemin ayrıntısı açılmaz.
return row.restricted ? (
<div className={cls}>{content}</div>
) : (
<button
type="button"
onClick={onOpen}
className={cn(cls, "outline-none hover:bg-muted/50 focus-visible:bg-muted")}
>
{content}
</button>
);
}
function ReconcileDialog({
open,
onOpenChange,
accountId,
isLiability,
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
accountId: string;
isLiability: boolean;
}) {
const [date, setDate] = useState(todayIstanbul);
const [balance, setBalance] = useState("");
const [preview, setPreview] = useState<ReconcilePreview | null>(null);
const [accept, setAccept] = useState(false);
const [errors, setErrors] = useState<Record<string, string | undefined>>({});
const [pending, setPending] = useState(false);
function reset(next: boolean) {
if (!next) {
setPreview(null);
setAccept(false);
setErrors({});
setBalance("");
setDate(todayIstanbul());
}
onOpenChange(next);
}
const input = () => ({
statementDate: date,
statementBalance: balance,
acceptAdjustment: accept,
});
async function check() {
setPending(true);
const res = await previewReconciliationAction(accountId, input());
setPending(false);
if (!res.ok) {
setErrors({ ...res.fieldErrors, root: res.fieldErrors ? undefined : res.error });
return;
}
setErrors({});
setAccept(false);
setPreview(res.data);
}
async function confirm() {
setPending(true);
const res = await reconcileAccountAction(accountId, input());
setPending(false);
if (!res.ok) {
setErrors({ root: res.error });
return;
}
toast.success(
res.data.adjustmentId
? r.doneWithAdjustment(res.data.markedCount)
: r.done(res.data.markedCount),
);
reset(false);
}
const diff = preview?.differenceMinor ?? 0;
const display = (minor: number) => formatMoney(isLiability ? -minor : minor);
return (
<ResponsiveDialog
open={open}
onOpenChange={reset}
title={r.title}
description={r.description}
footer={
<>
<Button variant="outline" type="button" onClick={() => reset(false)}>
{tr.common.cancel}
</Button>
{preview ? (
<Button onClick={confirm} disabled={pending || (diff !== 0 && !accept)}>
{pending ? <Loader2 className="animate-spin" /> : null}
{diff !== 0 ? r.confirmWithAdjustment : r.confirm}
</Button>
) : (
<Button onClick={check} disabled={pending || !balance.trim()}>
{pending ? <Loader2 className="animate-spin" /> : null}
{r.check}
</Button>
)}
</>
}
>
<FieldGroup>
<Field data-invalid={Boolean(errors.statementDate)}>
<FieldLabel htmlFor="rec-date">{r.date}</FieldLabel>
<Input
id="rec-date"
type="date"
value={date}
max={todayIstanbul()}
onChange={(e) => {
setDate(e.target.value);
setPreview(null);
}}
/>
{errors.statementDate ? <FieldError>{errors.statementDate}</FieldError> : null}
</Field>
<Field data-invalid={Boolean(errors.statementBalance)}>
<FieldLabel htmlFor="rec-balance">{isLiability ? r.debt : r.balance}</FieldLabel>
<MoneyInput
id="rec-balance"
value={balance}
allowNegative
onChange={(v) => {
setBalance(v);
setPreview(null);
}}
/>
<FieldDescription>{isLiability ? r.debtHint : r.balanceHint}</FieldDescription>
{errors.statementBalance ? <FieldError>{errors.statementBalance}</FieldError> : null}
</Field>
{preview ? (
<div className="flex flex-col gap-3 rounded-xl border p-3" aria-live="polite">
<dl className="grid grid-cols-3 gap-2 text-sm">
<div>
<dt className="text-xs text-muted-foreground">{r.statementBalance}</dt>
<dd className="tabular-nums">{display(preview.statementBalanceMinor)}</dd>
</div>
<div>
<dt className="text-xs text-muted-foreground">{r.appBalance}</dt>
<dd className="tabular-nums">{display(preview.appBalanceMinor)}</dd>
</div>
<div>
<dt className="text-xs text-muted-foreground">{r.difference}</dt>
<dd>
<SignedMoney minor={diff} />
</dd>
</div>
</dl>
{diff === 0 ? (
<p className="text-sm text-income">{r.matches}</p>
) : (
<>
<p className="text-sm text-expense">{r.mismatch}</p>
<label className="flex items-start gap-2 text-sm">
<Checkbox
checked={accept}
onCheckedChange={(v) => setAccept(v === true)}
className="mt-0.5"
/>
<span>
{r.adjustmentOffer(
formatMoney(Math.abs(diff)),
diff > 0 ? tr.transactions.types.income : tr.transactions.types.expense,
)}
</span>
</label>
</>
)}
<Badge variant="secondary" className="w-fit">
{r.unreconciled(preview.unreconciledCount)}
</Badge>
</div>
) : null}
{errors.root ? <FieldError>{errors.root}</FieldError> : null}
</FieldGroup>
</ResponsiveDialog>
);
}
@@ -27,6 +27,9 @@ import { cn } from "@/lib/utils";
import { todayIstanbul } from "@/shared/dates";
import { formatMoney } from "@/shared/format";
import { formatMoneyInput, parseMoney } from "@/shared/money";
import { allowedAttachmentKinds } from "@/shared/attachments";
import { AttachmentPicker } from "@/features/attachments/components/attachment-picker";
import type { AttachmentInfo } from "@/features/attachments/service";
import { transactionFormSchema, type TransactionForm } from "@/shared/schemas/transaction";
import { MAX_SPLITS, TRANSACTION_TYPES, type TransactionType } from "@/shared/transactions";
import {
@@ -57,6 +60,8 @@ type FormValues = {
payee: string;
description: string;
tags: string;
/** Önizleme bilgisiyle ekler; sunucuya yalnızca kimlikleri gider. */
attachments: AttachmentInfo[];
};
function toValues(mode: TransactionFormMode, options: TransactionFormOptions | null): FormValues {
@@ -72,6 +77,7 @@ function toValues(mode: TransactionFormMode, options: TransactionFormOptions | n
payee: "",
description: "",
tags: "",
attachments: [],
};
}
const x = mode.transaction;
@@ -90,6 +96,8 @@ function toValues(mode: TransactionFormMode, options: TransactionFormOptions | n
payee: x.payeeName,
description: x.description,
tags: x.tags.join(", "),
// Kopyada ekler taşınmaz (fiş o işleme aittir).
attachments: mode.kind === "edit" ? x.attachments : [],
};
}
@@ -298,6 +306,7 @@ export function TransactionFormDialog({
const [loadError, setLoadError] = useState<string | null>(null);
const [advancedOpen, setAdvancedOpen] = useState(false);
const [suggested, setSuggested] = useState(false);
const [uploadBusy, setUploadBusy] = 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<
@@ -332,6 +341,7 @@ export function TransactionFormDialog({
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 attachmentCount = useWatch({ control: form.control, name: "attachments" })?.length ?? 0;
const splitMode = splits.fields.length > 0;
// Düzenlemede arşivli/kapalı hesap veya kategori seçenek listesinde yoksa ekle (kaybolmasın).
@@ -431,9 +441,14 @@ export function TransactionFormDialog({
async function onSubmit() {
if (!mode) return;
const values = form.getValues();
if (uploadBusy) {
form.setError("root", { message: tr.attachments.waitForUploads });
return;
}
const { attachments, ...values } = form.getValues();
const payload = {
...values,
attachmentIds: attachments.map((a) => a.id),
toAccountId: values.type === "transfer" ? values.toAccountId : "",
categoryId: values.type === "transfer" || values.splits.length ? "" : values.categoryId,
splits: values.type === "transfer" ? [] : values.splits,
@@ -479,7 +494,7 @@ export function TransactionFormDialog({
<Button
type="submit"
form="transaction-form"
disabled={form.formState.isSubmitting || loading}
disabled={form.formState.isSubmitting || loading || uploadBusy}
>
{form.formState.isSubmitting ? <Loader2 className="animate-spin" /> : null}
{tr.common.save}
@@ -674,10 +689,30 @@ export function TransactionFormDialog({
· {t.list.split(splits.fields.length)}
</span>
) : null}
{attachmentCount ? (
<span className="text-xs text-muted-foreground">
· {tr.attachments.count(attachmentCount)}
</span>
) : null}
</Button>
</CollapsibleTrigger>
<CollapsibleContent className="pt-3">
<FieldGroup>
<Controller
name="attachments"
control={form.control}
render={({ field }) => (
<Field>
<FieldLabel>{tr.attachments.title}</FieldLabel>
<AttachmentPicker
value={field.value}
onChange={field.onChange}
allowedKinds={allowedAttachmentKinds(type)}
onBusyChange={setUploadBusy}
/>
</Field>
)}
/>
<Controller
name="tags"
control={form.control}
@@ -0,0 +1,344 @@
"use client";
import { ArrowLeftRight, CheckCheck, Copy, Pencil, Scale, Split, Trash2 } from "lucide-react";
import { useState, useTransition } from "react";
import { toast } from "sonner";
import { IconBadge } from "@/components/appearance/swatch";
import { useQuickAdd } from "@/components/layout/quick-add";
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 { Skeleton } from "@/components/ui/skeleton";
import { AttachmentStrip } from "@/features/attachments/components/attachment-strip";
import { tr } from "@/i18n/tr";
import { cn } from "@/lib/utils";
import { formatDate, formatDateTime, formatMoney } from "@/shared/format";
import type { TransactionType } from "@/shared/transactions";
import { getTransactionAction, setTransactionDeletedAction } from "../actions";
import type { TransactionDetail, TransactionListItem } from "../service";
/** İşlem listesi, ayrıntı ve hesap ekstresinin paylaştığı parçalar. */
const t = tr.transactions;
const weekday = new Intl.DateTimeFormat("tr-TR", { weekday: "long", timeZone: "Europe/Istanbul" });
/** "2026-11-05" → "05.11.2026 · Perşembe" */
export function dayLabel(ymd: string) {
const d = new Date(`${ymd}T12:00:00+03:00`);
return `${formatDate(d)} · ${weekday.format(d)}`;
}
export function signed(type: TransactionType, amountMinor: number) {
return type === "income" ? amountMinor : type === "expense" ? -amountMinor : 0;
}
export 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>
);
}
export 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.isAdjustment) {
return (
<span className="inline-flex size-9 shrink-0 items-center justify-center rounded-full bg-muted text-muted-foreground">
<Scale 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" />
);
}
export function rowTitle(item: TransactionListItem) {
if (item.isAdjustment) return t.adjustment;
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];
}
export function rowSubtitle(item: TransactionListItem) {
if (item.type === "transfer")
return t.list.transfer(item.account.name, item.toAccount?.name ?? "—");
const what = item.isAdjustment
? item.description
: item.splitCount
? t.list.split(item.splitCount)
: (item.category?.path ?? "—");
return `${what} · ${item.account.name}`;
}
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>
{/* Mutabakat düzeltmesi düzenlenemez/kopyalanamaz; yalnızca silinebilir. */}
{detail.isAdjustment ? null : (
<>
<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.isAdjustment ? row(t.fields.category, t.adjustment) : 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}
{detail.attachments.length
? row(
tr.attachments.title,
<span className="flex justify-end">
<AttachmentStrip items={detail.attachments} />
</span>,
)
: null}
{detail.reconciledAccountIds.length
? row(
tr.statement.reconcile.title,
<span className="inline-flex items-center gap-1 text-income">
<CheckCheck className="size-4" aria-hidden />
{t.reconciled}
</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>
);
}
/**
* Ayrıntı penceresi + silme onayı + geri al bildirimi. Liste ve ekstre aynı davranışı kullanır;
* düzenle/kopyala uygulama genelindeki işlem formunu açar.
*/
export function useTransactionDetail(canWrite: boolean) {
const { openTransactionForm } = useQuickAdd();
const [detail, setDetail] = useState<TransactionDetail | null>(null);
const [loading, setLoading] = useState(false);
const [deleting, setDeleting] = useState<TransactionDetail | null>(null);
const [, startTransition] = useTransition();
async function openDetail(id: string) {
setLoading(true);
setDetail(null);
const res = await getTransactionAction(id);
setLoading(false);
if (res.ok) setDetail(res.data);
else toast.error(res.error);
}
function close() {
setDetail(null);
setLoading(false);
}
function remove(d: TransactionDetail) {
setDeleting(null);
close();
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);
},
},
});
});
}
const element = (
<>
<DetailDialog
detail={detail}
loading={loading}
canWrite={canWrite}
onOpenChange={(o) => !o && close()}
onEdit={(d) => {
close();
openTransactionForm({ kind: "edit", transaction: d });
}}
onCopy={(d) => {
close();
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>
</>
);
return { openDetail, element };
}
@@ -1,36 +1,12 @@
"use client";
import {
ArrowLeftRight,
ChevronLeft,
ChevronRight,
Copy,
Download,
Filter,
Paperclip,
Pencil,
Plus,
Split,
Trash2,
X,
} from "lucide-react";
import { ChevronLeft, ChevronRight, Download, Filter, Paperclip, Plus, 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 { useState } from "react";
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";
@@ -43,103 +19,24 @@ import {
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 { formatMoney } from "@/shared/format";
import type { TransactionFilters } from "@/shared/schemas/transaction";
import { TRANSACTION_STATUSES, TRANSACTION_TYPES } from "@/shared/transactions";
import type { TransactionFormOptions, TransactionListItem, TransactionPage } from "../service";
import {
TRANSACTION_STATUSES,
TRANSACTION_TYPES,
type TransactionType,
} from "@/shared/transactions";
import { getTransactionAction, setTransactionDeletedAction } from "../actions";
import type {
TransactionDetail,
TransactionFormOptions,
TransactionListItem,
TransactionPage,
} from "../service";
Amount,
dayLabel,
RowIcon,
rowSubtitle,
rowTitle,
signed,
useTransactionDetail,
} from "./transaction-parts";
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 ---
@@ -318,126 +215,6 @@ function FiltersDialog({
// --- 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({
@@ -454,12 +231,9 @@ export function TransactionsView({
canWrite: boolean;
}) {
const pathname = usePathname();
const { openQuickAdd, openTransactionForm } = useQuickAdd();
const { openQuickAdd } = 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 { openDetail, element: detailElement } = useTransactionDetail(canWrite);
const active = countActive(filters);
const pageHref = (page: number) => {
@@ -474,40 +248,6 @@ export function TransactionsView({
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) {
@@ -679,35 +419,7 @@ export function TransactionsView({
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>
{detailElement}
</div>
);
}
+87 -1
View File
@@ -256,7 +256,7 @@ export const tr = {
description: "Açıklama",
tags: "Etiketler",
tagsHint: "Virgülle ayırın (ör. tatil, indirim)",
advanced: "Gelişmiş: etiket, bölme",
advanced: "Gelişmiş: ek, etiket, bölme",
split: "Bölünmüş işlem",
splitHint: "Tutarı birden çok kategoriye bölün; kalemlerin toplamı tutara eşit olmalı.",
addSplit: "Kalem ekle",
@@ -344,10 +344,96 @@ export const tr = {
],
filename: (date: string) => `butcem-islemler-${date}.csv`,
},
adjustment: "Mutabakat düzeltmesi",
adjustmentReadOnly:
"Mutabakat düzeltmesi düzenlenemez; gerekirse silip mutabakatı yeniden yapın.",
reconciled: "Mutabakatı yapıldı",
readOnly: "İzleyici rolündesiniz; işlem ekleyemezsiniz.",
noAccounts: "İşlem girmek için önce bir hesap gerekli.",
noAccountsLink: "Hesaplara git",
},
attachments: {
title: "Ekler",
add: "Ek ekle",
addHint: { image: "Fiş veya fatura fotoğrafı", imagePdf: "Görsel veya PDF (ör. bordro)" },
count: (n: number) => `${n} ek`,
uploading: "Yükleniyor…",
remove: "Eki kaldır",
open: "Aç",
download: "İndir",
fullscreen: "Tam ekran",
exitFullscreen: "Tam ekrandan çık",
previous: "Önceki",
next: "Sonraki",
position: (i: number, n: number) => `${i} / ${n}`,
viewerTitle: "Ek dosyalar",
pdf: "PDF belgesi",
moreCount: (n: number) => `+${n}`,
waitForUploads: "Yüklemeler bitmeden kaydedilemez.",
errors: {
empty: "Dosya seçilmedi veya dosya boş.",
tooLarge: (mb: number) => `Dosya çok büyük (en fazla ${mb} MB).`,
tooMany: (n: number) => `Bir kayda en fazla ${n} dosya eklenebilir.`,
tooManyPending: "Kaydedilmemiş çok fazla ek var; önce formu kaydedin.",
unsupported: "Desteklenmeyen dosya türü. JPEG, PNG, WebP, HEIC veya PDF yükleyin.",
unreadable: "Dosya okunamadı veya bozuk.",
kindNotAllowed: "Gider işlemlerine yalnızca görsel eklenebilir (PDF gelir ve transferlerde).",
invalid: "Ek dosya bulunamadı veya bu kayda eklenemez.",
upload: "Dosya yüklenemedi.",
},
},
statement: {
title: "Hesap ekstresi",
back: "Hesaplar",
allTransactions: "Tüm işlemler",
prevMonth: "Önceki ay",
nextMonth: "Sonraki ay",
opening: "Ay başı bakiye",
inflow: "Giriş",
outflow: "Çıkış",
closing: "Ay sonu bakiye",
current: "Güncel bakiye",
balanceAfter: "Bakiye",
empty: "Bu ayda işlem yok.",
truncated: "Çok fazla işlem var; yalnızca ilk 2.000 işlem gösteriliyor.",
lastReconciliation: (date: string, balance: string) =>
`Son mutabakat: ${date} · ekstre bakiyesi ${balance}`,
noReconciliation: "Henüz mutabakat yapılmadı.",
reconciledHint: "Mutabakatı yapılmış işlem",
adjustmentDescription: (statementBalance: string) =>
`Ekstre bakiyesi ${statementBalance} ile fark`,
reconcile: {
open: "Mutabakat yap",
title: "Mutabakat",
description:
"Banka veya kart ekstrenizdeki tarihi ve bakiyeyi girin; uygulamadaki bakiye ile karşılaştırılır.",
date: "Ekstre tarihi",
balance: "Ekstredeki bakiye (TL)",
debt: "Ekstredeki borç (TL)",
balanceHint: "Eksi bakiye için başına - koyun (ör. KMH kullanımı).",
debtHint: "Karttaki toplam borcu pozitif girin.",
check: "Karşılaştır",
statementBalance: "Ekstre",
appBalance: "Uygulama",
difference: "Fark",
matches: "Bakiyeler tutuyor.",
mismatch: "Bakiyeler tutmuyor. Eksik veya hatalı işlem olabilir.",
adjustmentOffer: (amount: string, kind: string) =>
`Farkı kapatmak için ${amount} tutarında bir “${kind}” düzeltme işlemi oluşturulsun.`,
acceptAdjustment: "Düzeltme işlemi oluştur",
unreconciled: (n: number) => `${n} işlem işaretlenecek.`,
confirm: "Mutabakatı tamamla",
confirmWithAdjustment: "Düzelt ve tamamla",
done: (n: number) => `Mutabakat tamamlandı; ${n} işlem işaretlendi.`,
doneWithAdjustment: (n: number) => `Düzeltme işlemi oluşturuldu ve ${n} işlem işaretlendi.`,
},
errors: {
date: "Geçerli ve bugünden ileri olmayan bir tarih girin.",
archived: "Arşivlenmiş hesapta mutabakat yapılamaz.",
needsAdjustment:
"Bakiyeler tutmuyor; düzeltme işlemini onaylayın veya işlemleri kontrol edin.",
},
},
categories: {
title: "Kategoriler",
description: "Gelir ve gider kategorileri. Alt kategoriler raporlarda üst kategoriye toplanır.",