feat(finance): income/expense/debt/receivable tracking + summary

Multi-tenant cash flow tracker. All amounts in TRY, decimals preserved.

Schema/validation:
- lib/validation/finance.ts: financeEntrySchema with type enum, positive
  amount, date required, optional customer/invoice link, optional payment
  method.
- lib/appwrite/finance-actions.ts: create/update/delete with audit; date
  HTML input normalized to ISO before write.
- lib/appwrite/finance-queries.ts: listFinanceEntries ordered by date desc.

UI:
- /finance server page passes entries + customers to FinanceClient.
- 5 stat cards: Gelir / Gider / Net (income-expense, color-coded by sign)
  / Alacaklar / Borçlar.
- Type filter dropdown (Tümü/Gelir/Gider/Alacaklar/Borçlar) + global
  search (description/customer/amount).
- 4 quick-add buttons let users start a new entry pre-filled with the
  desired type. Single FinanceFormSheet handles all 4 types via a Select.
- Table: type badge (color-coded), signed amount (+ for income/receivable,
  − for expense/debt), date, customer, payment method label, description
  preview. Row dropdown: Edit / Delete.
- Inline destructive Sil button in Sheet footer when editing.
This commit is contained in:
kovakmedya
2026-04-30 06:04:46 +03:00
parent b4c1073d91
commit 98ab73235f
8 changed files with 1003 additions and 0 deletions
@@ -0,0 +1,429 @@
"use client";
import { useMemo, useState, useTransition } from "react";
import {
type ColumnDef,
flexRender,
getCoreRowModel,
getFilteredRowModel,
getPaginationRowModel,
getSortedRowModel,
useReactTable,
type SortingState,
} from "@tanstack/react-table";
import {
ArrowDownCircle,
ArrowUpCircle,
CircleAlert,
CircleDollarSign,
Loader2,
MoreHorizontal,
Pencil,
Plus,
Search,
Trash2,
Wallet,
} from "lucide-react";
import { toast } from "sonner";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { deleteFinanceEntryAction } from "@/lib/appwrite/finance-actions";
import { formatDate, formatTRY } from "@/lib/format";
import { cn } from "@/lib/utils";
import { FinanceFormSheet } from "./finance-form-sheet";
import {
type Customer,
type FinanceRow,
type FinanceType,
PAYMENT_METHOD_LABEL,
TYPE_COLOR,
TYPE_LABEL,
} from "./types";
type Props = {
entries: FinanceRow[];
customers: Customer[];
};
function StatCard({
label,
amount,
icon: Icon,
tone,
}: {
label: string;
amount: number;
icon: typeof Wallet;
tone: "income" | "expense" | "receivable" | "debt" | "net";
}) {
const toneClass = {
income: "text-emerald-600 dark:text-emerald-400",
expense: "text-red-600 dark:text-red-400",
receivable: "text-blue-600 dark:text-blue-400",
debt: "text-amber-600 dark:text-amber-400",
net: amount >= 0 ? "text-emerald-600 dark:text-emerald-400" : "text-red-600 dark:text-red-400",
}[tone];
return (
<Card>
<CardContent className="flex items-start justify-between p-4">
<div>
<p className="text-muted-foreground text-xs">{label}</p>
<p className={cn("mt-1 text-xl font-semibold", toneClass)}>{formatTRY(amount)}</p>
</div>
<Icon className={cn("size-5", toneClass)} />
</CardContent>
</Card>
);
}
export function FinanceClient({ entries, customers }: Props) {
const [tab, setTab] = useState<FinanceType | "all">("all");
const [search, setSearch] = useState("");
const [sorting, setSorting] = useState<SortingState>([]);
const [formOpen, setFormOpen] = useState(false);
const [editing, setEditing] = useState<FinanceRow | null>(null);
const [defaultType, setDefaultType] = useState<FinanceType>("income");
const [deleting, setDeleting] = useState<FinanceRow | null>(null);
const [busy, startTransition] = useTransition();
const stats = useMemo(() => {
let income = 0,
expense = 0,
receivable = 0,
debt = 0;
for (const e of entries) {
if (e.type === "income") income += e.amount;
else if (e.type === "expense") expense += e.amount;
else if (e.type === "receivable") receivable += e.amount;
else if (e.type === "debt") debt += e.amount;
}
return { income, expense, receivable, debt, net: income - expense };
}, [entries]);
const filtered = useMemo(
() => (tab === "all" ? entries : entries.filter((e) => e.type === tab)),
[entries, tab],
);
const columns = useMemo<ColumnDef<FinanceRow>[]>(
() => [
{
accessorKey: "type",
header: "Tür",
cell: ({ row }) => (
<Badge variant="outline" className={cn("border-0", TYPE_COLOR[row.original.type])}>
{TYPE_LABEL[row.original.type]}
</Badge>
),
},
{
accessorKey: "amount",
header: "Tutar",
cell: ({ row }) => {
const sign =
row.original.type === "income" || row.original.type === "receivable" ? "+" : "";
return (
<span className="font-medium tabular-nums">
{sign} {formatTRY(row.original.amount)}
</span>
);
},
},
{
accessorKey: "date",
header: "Tarih",
cell: ({ row }) => (
<span className="text-muted-foreground">{formatDate(row.original.date)}</span>
),
},
{
accessorKey: "customerName",
header: "Müşteri",
cell: ({ row }) =>
row.original.customerName ? (
<span>{row.original.customerName}</span>
) : (
<span className="text-muted-foreground"></span>
),
},
{
accessorKey: "paymentMethod",
header: "Ödeme",
cell: ({ row }) => (
<span className="text-muted-foreground text-sm">
{PAYMENT_METHOD_LABEL[row.original.paymentMethod]}
</span>
),
},
{
accessorKey: "description",
header: "Açıklama",
cell: ({ row }) =>
row.original.description ? (
<span className="text-muted-foreground line-clamp-1 max-w-[260px] text-sm">
{row.original.description}
</span>
) : (
<span className="text-muted-foreground"></span>
),
},
{
id: "actions",
cell: ({ row }) => (
<div className="flex justify-end">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="size-8">
<MoreHorizontal className="size-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
onClick={() => {
setEditing(row.original);
setFormOpen(true);
}}
>
<Pencil className="size-3.5" />
Düzenle
</DropdownMenuItem>
<DropdownMenuItem
variant="destructive"
onClick={() => setDeleting(row.original)}
>
<Trash2 className="size-3.5" />
Sil
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
),
},
],
[],
);
const table = useReactTable({
data: filtered,
columns,
state: { globalFilter: search, sorting },
onGlobalFilterChange: setSearch,
onSortingChange: setSorting,
getCoreRowModel: getCoreRowModel(),
getFilteredRowModel: getFilteredRowModel(),
getSortedRowModel: getSortedRowModel(),
getPaginationRowModel: getPaginationRowModel(),
initialState: { pagination: { pageSize: 25 } },
globalFilterFn: (row, _id, fv) => {
const v = String(fv).toLowerCase();
return [row.original.description, row.original.customerName, row.original.amount.toString()]
.join(" ")
.toLowerCase()
.includes(v);
},
});
const handleDelete = () => {
if (!deleting) return;
startTransition(async () => {
const fd = new FormData();
fd.set("id", deleting.id);
const result = await deleteFinanceEntryAction(fd);
if (result.ok) {
toast.success("Kayıt silindi.");
setDeleting(null);
} else {
toast.error(result.error ?? "Silme başarısız.");
}
});
};
const openCreate = (type: FinanceType) => {
setEditing(null);
setDefaultType(type);
setFormOpen(true);
};
return (
<>
<div className="grid grid-cols-2 gap-3 md:grid-cols-5">
<StatCard
label="Gelir"
amount={stats.income}
icon={ArrowUpCircle}
tone="income"
/>
<StatCard
label="Gider"
amount={stats.expense}
icon={ArrowDownCircle}
tone="expense"
/>
<StatCard label="Net" amount={stats.net} icon={CircleDollarSign} tone="net" />
<StatCard
label="Alacaklar"
amount={stats.receivable}
icon={Wallet}
tone="receivable"
/>
<StatCard label="Borçlar" amount={stats.debt} icon={CircleAlert} tone="debt" />
</div>
<Card>
<CardContent className="p-0">
<div className="flex flex-col gap-3 p-4 md:flex-row md:items-center md:justify-between">
<div className="flex items-center gap-2">
<Select value={tab} onValueChange={(v) => setTab(v as typeof tab)}>
<SelectTrigger className="w-[160px]">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">Tümü</SelectItem>
<SelectItem value="income">Gelir</SelectItem>
<SelectItem value="expense">Gider</SelectItem>
<SelectItem value="receivable">Alacaklar</SelectItem>
<SelectItem value="debt">Borçlar</SelectItem>
</SelectContent>
</Select>
<div className="relative md:max-w-xs md:flex-1">
<Search className="text-muted-foreground absolute top-1/2 left-3 size-4 -translate-y-1/2" />
<Input
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Açıklama, müşteri, tutar..."
className="pl-9"
/>
</div>
</div>
<div className="flex flex-wrap gap-2">
<Button variant="outline" size="sm" onClick={() => openCreate("income")}>
<Plus className="size-3.5" />
Gelir
</Button>
<Button variant="outline" size="sm" onClick={() => openCreate("expense")}>
<Plus className="size-3.5" />
Gider
</Button>
<Button variant="outline" size="sm" onClick={() => openCreate("receivable")}>
<Plus className="size-3.5" />
Alacak
</Button>
<Button variant="outline" size="sm" onClick={() => openCreate("debt")}>
<Plus className="size-3.5" />
Borç
</Button>
</div>
</div>
<Table>
<TableHeader>
{table.getHeaderGroups().map((hg) => (
<TableRow key={hg.id}>
{hg.headers.map((h) => (
<TableHead key={h.id}>
{h.isPlaceholder
? null
: flexRender(h.column.columnDef.header, h.getContext())}
</TableHead>
))}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows.length ? (
table.getRowModel().rows.map((r) => (
<TableRow key={r.id}>
{r.getVisibleCells().map((c) => (
<TableCell key={c.id}>
{flexRender(c.column.columnDef.cell, c.getContext())}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={columns.length} className="h-32 text-center">
<p className="text-muted-foreground text-sm">Kayıt yok.</p>
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</CardContent>
</Card>
<FinanceFormSheet
open={formOpen}
onOpenChange={(v) => {
setFormOpen(v);
if (!v) setEditing(null);
}}
entry={editing}
defaultType={defaultType}
customers={customers}
onRequestDelete={(e) => {
setFormOpen(false);
setDeleting(e);
}}
/>
<Dialog open={Boolean(deleting)} onOpenChange={(v) => !v && setDeleting(null)}>
<DialogContent>
<DialogHeader>
<DialogTitle>Kaydı sil</DialogTitle>
<DialogDescription>
{deleting && (
<>
<strong>{TYPE_LABEL[deleting.type]}</strong> {formatTRY(deleting.amount)} (
{formatDate(deleting.date)}) silinecek.
</>
)}
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={() => setDeleting(null)} disabled={busy}>
Vazgeç
</Button>
<Button variant="destructive" onClick={handleDelete} disabled={busy}>
{busy ? <Loader2 className="size-4 animate-spin" /> : <Trash2 className="size-4" />}
Sil
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
);
}
@@ -0,0 +1,236 @@
"use client";
import { useActionState, useEffect } from "react";
import { Loader2, Save, Trash2 } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
Sheet,
SheetContent,
SheetDescription,
SheetFooter,
SheetHeader,
SheetTitle,
} from "@/components/ui/sheet";
import { Textarea } from "@/components/ui/textarea";
import {
createFinanceEntryAction,
updateFinanceEntryAction,
} from "@/lib/appwrite/finance-actions";
import { initialFinanceState } from "@/lib/appwrite/finance-types";
import type { Customer, FinanceRow, FinanceType } from "./types";
const NONE = "__none__";
type Props = {
open: boolean;
onOpenChange: (v: boolean) => void;
entry?: FinanceRow | null;
defaultType?: FinanceType;
customers: Customer[];
onRequestDelete?: (entry: FinanceRow) => void;
};
function isoToDate(iso: string): string {
if (!iso) return "";
return iso.slice(0, 10);
}
export function FinanceFormSheet({
open,
onOpenChange,
entry,
defaultType = "income",
customers,
onRequestDelete,
}: Props) {
const isEdit = Boolean(entry);
const action = isEdit ? updateFinanceEntryAction : createFinanceEntryAction;
const [state, formAction, isPending] = useActionState(action, initialFinanceState);
useEffect(() => {
if (state.ok) {
toast.success(isEdit ? "Kayıt güncellendi." : "Kayıt eklendi.");
onOpenChange(false);
} else if (state.error) {
toast.error(state.error);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [state]);
const today = new Date().toISOString().slice(0, 10);
return (
<Sheet open={open} onOpenChange={onOpenChange}>
<SheetContent className="flex w-full flex-col gap-0 p-0 sm:max-w-xl">
<SheetHeader className="border-b px-6 py-4">
<SheetTitle>{isEdit ? "Kaydı düzenle" : "Yeni kayıt"}</SheetTitle>
<SheetDescription>
Gelir, gider, borç veya alacak girişi. Borç = ödeyeceğiniz, Alacak = tahsil edeceğiniz.
</SheetDescription>
</SheetHeader>
<form
action={(fd) => {
["customerId", "paymentMethod"].forEach((k) => {
if (fd.get(k) === NONE) fd.set(k, "");
});
formAction(fd);
}}
className="flex flex-1 flex-col"
>
{isEdit && entry && <input type="hidden" name="id" value={entry.id} />}
<div className="flex-1 space-y-4 overflow-y-auto px-6 py-5">
<div className="grid gap-4 md:grid-cols-2">
<div className="grid gap-2">
<Label htmlFor="type">Tür *</Label>
<Select name="type" defaultValue={entry?.type ?? defaultType}>
<SelectTrigger id="type">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="income">Gelir</SelectItem>
<SelectItem value="expense">Gider</SelectItem>
<SelectItem value="receivable">Alacak</SelectItem>
<SelectItem value="debt">Borç</SelectItem>
</SelectContent>
</Select>
</div>
<div className="grid gap-2">
<Label htmlFor="amount">Tutar () *</Label>
<Input
id="amount"
name="amount"
type="number"
step="0.01"
min="0.01"
defaultValue={entry?.amount ?? ""}
placeholder="0.00"
required
/>
{state.fieldErrors?.amount && (
<p className="text-destructive text-xs">{state.fieldErrors.amount}</p>
)}
</div>
</div>
<div className="grid gap-4 md:grid-cols-2">
<div className="grid gap-2">
<Label htmlFor="date">Tarih *</Label>
<Input
id="date"
name="date"
type="date"
defaultValue={isoToDate(entry?.date ?? today)}
required
/>
</div>
<div className="grid gap-2">
<Label htmlFor="paymentMethod">Ödeme yöntemi</Label>
<Select
name="paymentMethod"
defaultValue={entry?.paymentMethod || NONE}
>
<SelectTrigger id="paymentMethod">
<SelectValue placeholder="Belirtilmemiş" />
</SelectTrigger>
<SelectContent>
<SelectItem value={NONE}>Belirtilmemiş</SelectItem>
<SelectItem value="cash">Nakit</SelectItem>
<SelectItem value="transfer">Havale / EFT</SelectItem>
<SelectItem value="card">Kart</SelectItem>
<SelectItem value="check">Çek</SelectItem>
<SelectItem value="other">Diğer</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<div className="grid gap-2">
<Label htmlFor="customerId">Müşteri (opsiyonel)</Label>
<Select name="customerId" defaultValue={entry?.customerId || NONE}>
<SelectTrigger id="customerId">
<SelectValue placeholder="Yok" />
</SelectTrigger>
<SelectContent>
<SelectItem value={NONE}>Yok</SelectItem>
{customers.map((c) => (
<SelectItem key={c.id} value={c.id}>
{c.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="grid gap-2">
<Label htmlFor="description">Açıklama</Label>
<Textarea
id="description"
name="description"
rows={3}
defaultValue={entry?.description ?? ""}
placeholder="Hangi kalem, hangi fatura, vb."
/>
</div>
</div>
<SheetFooter className="border-t bg-muted/30 px-6 py-4">
<div className="flex w-full items-center justify-between gap-2">
<div>
{isEdit && entry && onRequestDelete && (
<Button
type="button"
variant="ghost"
size="sm"
className="text-destructive hover:text-destructive"
onClick={() => onRequestDelete(entry)}
disabled={isPending}
>
<Trash2 className="size-3.5" />
Sil
</Button>
)}
</div>
<div className="flex gap-2">
<Button
type="button"
variant="outline"
onClick={() => onOpenChange(false)}
disabled={isPending}
>
Vazgeç
</Button>
<Button type="submit" disabled={isPending}>
{isPending ? (
<>
<Loader2 className="size-4 animate-spin" />
Kaydediliyor...
</>
) : (
<>
<Save className="size-4" />
{isEdit ? "Güncelle" : "Kaydet"}
</>
)}
</Button>
</div>
</div>
</SheetFooter>
</form>
</SheetContent>
</Sheet>
);
}
@@ -0,0 +1,38 @@
export type FinanceType = "income" | "expense" | "debt" | "receivable";
export type PaymentMethod = "cash" | "transfer" | "card" | "check" | "other" | "";
export type FinanceRow = {
id: string;
type: FinanceType;
amount: number;
date: string;
description: string;
customerId: string;
customerName: string;
paymentMethod: PaymentMethod;
};
export type Customer = { id: string; name: string };
export const TYPE_LABEL: Record<FinanceType, string> = {
income: "Gelir",
expense: "Gider",
debt: "Borç",
receivable: "Alacak",
};
export const TYPE_COLOR: Record<FinanceType, string> = {
income: "bg-emerald-500/15 text-emerald-700 dark:text-emerald-300 border-emerald-500/30",
expense: "bg-red-500/15 text-red-700 dark:text-red-300 border-red-500/30",
debt: "bg-amber-500/15 text-amber-800 dark:text-amber-300 border-amber-500/30",
receivable: "bg-blue-500/15 text-blue-700 dark:text-blue-300 border-blue-500/30",
};
export const PAYMENT_METHOD_LABEL: Record<PaymentMethod, string> = {
cash: "Nakit",
transfer: "Havale / EFT",
card: "Kart",
check: "Çek",
other: "Diğer",
"": "—",
};
+53
View File
@@ -0,0 +1,53 @@
import type { Metadata } from "next";
import { redirect } from "next/navigation";
import { listCustomers } from "@/lib/appwrite/customer-queries";
import { listFinanceEntries } from "@/lib/appwrite/finance-queries";
import { requireTenant } from "@/lib/appwrite/tenant-guard";
import { FinanceClient } from "./components/finance-client";
export const metadata: Metadata = {
title: "İşletmem — Gelir / Gider",
};
export default async function FinancePage() {
let ctx;
try {
ctx = await requireTenant();
} catch {
redirect("/onboarding");
}
const [entries, customers] = await Promise.all([
listFinanceEntries(ctx.tenantId),
listCustomers(ctx.tenantId),
]);
const customerMap = new Map(customers.map((c) => [c.$id, c.name]));
return (
<div className="flex-1 space-y-6 px-6 pt-0">
<div className="flex flex-col gap-1">
<p className="text-muted-foreground text-sm">{ctx.settings?.companyName ?? "Çalışma alanı"}</p>
<h1 className="text-2xl font-bold tracking-tight">Gelir / Gider</h1>
<p className="text-muted-foreground text-sm">
Nakit hareketleri, borç ve alacaklarınızı tek yerden takip edin.
</p>
</div>
<FinanceClient
entries={entries.map((e) => ({
id: e.$id,
type: e.type,
amount: e.amount,
date: e.date,
description: e.description ?? "",
customerId: e.customerId ?? "",
customerName: e.customerId ? customerMap.get(e.customerId) ?? "" : "",
paymentMethod: e.paymentMethod ?? "",
}))}
customers={customers.map((c) => ({ id: c.$id, name: c.name }))}
/>
</div>
);
}
+197
View File
@@ -0,0 +1,197 @@
"use server";
import { revalidatePath } from "next/cache";
import { AppwriteException, ID, Permission, Role } from "node-appwrite";
import { z } from "zod";
import { logAudit } from "./audit";
import { DATABASE_ID, TABLES, type FinanceEntry } from "./schema";
import { createAdminClient } from "./server";
import { requireTenant } from "./tenant-guard";
import type { FinanceActionState } from "./finance-types";
import { financeEntrySchema } from "@/lib/validation/finance";
function appwriteError(e: unknown): string {
if (e instanceof AppwriteException) return e.message || "Beklenmeyen hata.";
return "Bağlantı hatası. Tekrar deneyin.";
}
function flattenErrors(err: z.ZodError): Record<string, string> {
const out: Record<string, string> = {};
for (const issue of err.issues) {
const key = issue.path.join(".");
if (key && !out[key]) out[key] = issue.message;
}
return out;
}
function teamRowPermissions(tenantId: string) {
return [
Permission.read(Role.team(tenantId)),
Permission.update(Role.team(tenantId)),
Permission.delete(Role.team(tenantId, "owner")),
Permission.delete(Role.team(tenantId, "admin")),
];
}
function pickFormFields(formData: FormData) {
return {
type: formData.get("type") as "income" | "expense" | "debt" | "receivable",
amount: String(formData.get("amount") ?? "0"),
date: String(formData.get("date") ?? ""),
description: String(formData.get("description") ?? "").trim(),
customerId: String(formData.get("customerId") ?? ""),
invoiceId: String(formData.get("invoiceId") ?? ""),
paymentMethod: formData.get("paymentMethod") as
| "cash"
| "transfer"
| "card"
| "check"
| "other"
| null,
};
}
function toIso(v: string): string {
if (!v) return v;
if (/^\d{4}-\d{2}-\d{2}$/.test(v)) return `${v}T00:00:00.000+00:00`;
return v;
}
export async function createFinanceEntryAction(
_prev: FinanceActionState,
formData: FormData,
): Promise<FinanceActionState> {
let ctx;
try {
ctx = await requireTenant();
} catch {
return { ok: false, error: "Yetkiniz yok." };
}
const parsed = financeEntrySchema.safeParse(pickFormFields(formData));
if (!parsed.success) {
return { ok: false, error: "Form geçersiz.", fieldErrors: flattenErrors(parsed.error) };
}
try {
const { tablesDB } = createAdminClient();
const data = { ...parsed.data, date: toIso(parsed.data.date) };
const row = await tablesDB.createRow(
DATABASE_ID,
TABLES.financeEntries,
ID.unique(),
{
tenantId: ctx.tenantId,
createdBy: ctx.user.id,
...data,
},
teamRowPermissions(ctx.tenantId),
);
await logAudit({
tenantId: ctx.tenantId,
userId: ctx.user.id,
action: "create",
entityType: "finance_entry",
entityId: row.$id,
changes: data,
});
} catch (e) {
return { ok: false, error: appwriteError(e) };
}
revalidatePath("/finance");
return { ok: true };
}
export async function updateFinanceEntryAction(
_prev: FinanceActionState,
formData: FormData,
): Promise<FinanceActionState> {
const id = String(formData.get("id") ?? "");
if (!id) return { ok: false, error: "ID eksik." };
let ctx;
try {
ctx = await requireTenant();
} catch {
return { ok: false, error: "Yetkiniz yok." };
}
const parsed = financeEntrySchema.safeParse(pickFormFields(formData));
if (!parsed.success) {
return { ok: false, error: "Form geçersiz.", fieldErrors: flattenErrors(parsed.error) };
}
try {
const { tablesDB } = createAdminClient();
const existing = (await tablesDB.getRow(
DATABASE_ID,
TABLES.financeEntries,
id,
)) as unknown as FinanceEntry;
if (existing.tenantId !== ctx.tenantId) {
return { ok: false, error: "Erişim engellendi." };
}
const data = { ...parsed.data, date: toIso(parsed.data.date) };
await tablesDB.updateRow(DATABASE_ID, TABLES.financeEntries, id, data);
await logAudit({
tenantId: ctx.tenantId,
userId: ctx.user.id,
action: "update",
entityType: "finance_entry",
entityId: id,
changes: data,
});
} catch (e) {
return { ok: false, error: appwriteError(e) };
}
revalidatePath("/finance");
return { ok: true };
}
export async function deleteFinanceEntryAction(
formData: FormData,
): Promise<FinanceActionState> {
const id = String(formData.get("id") ?? "");
if (!id) return { ok: false, error: "ID eksik." };
let ctx;
try {
ctx = await requireTenant();
} catch {
return { ok: false, error: "Yetkiniz yok." };
}
try {
const { tablesDB } = createAdminClient();
const existing = (await tablesDB.getRow(
DATABASE_ID,
TABLES.financeEntries,
id,
)) as unknown as FinanceEntry;
if (existing.tenantId !== ctx.tenantId) {
return { ok: false, error: "Erişim engellendi." };
}
await tablesDB.deleteRow(DATABASE_ID, TABLES.financeEntries, id);
await logAudit({
tenantId: ctx.tenantId,
userId: ctx.user.id,
action: "delete",
entityType: "finance_entry",
entityId: id,
changes: { type: existing.type, amount: existing.amount },
});
} catch (e) {
return { ok: false, error: appwriteError(e) };
}
revalidatePath("/finance");
return { ok: true };
}
+24
View File
@@ -0,0 +1,24 @@
import "server-only";
import { Query } from "node-appwrite";
import { createAdminClient } from "./server";
import { DATABASE_ID, TABLES, type FinanceEntry } from "./schema";
export async function listFinanceEntries(tenantId: string): Promise<FinanceEntry[]> {
try {
const { tablesDB } = createAdminClient();
const result = await tablesDB.listRows({
databaseId: DATABASE_ID,
tableId: TABLES.financeEntries,
queries: [
Query.equal("tenantId", tenantId),
Query.orderDesc("date"),
Query.limit(1000),
],
});
return result.rows as unknown as FinanceEntry[];
} catch {
return [];
}
}
+7
View File
@@ -0,0 +1,7 @@
export type FinanceActionState = {
ok: boolean;
error?: string;
fieldErrors?: Record<string, string>;
};
export const initialFinanceState: FinanceActionState = { ok: false };
+19
View File
@@ -0,0 +1,19 @@
import { z } from "zod";
export const financeEntrySchema = z.object({
type: z.enum(["income", "expense", "debt", "receivable"]),
amount: z
.union([z.number(), z.string()])
.transform((v) => (typeof v === "string" ? Number(v.replace(",", ".")) : v))
.pipe(z.number().positive("Tutar 0'dan büyük olmalı.")),
date: z.string().min(1, "Tarih zorunlu."),
description: z.string().trim().max(1000).optional().transform((v) => (v ? v : undefined)),
customerId: z.string().optional().transform((v) => (v ? v : undefined)),
invoiceId: z.string().optional().transform((v) => (v ? v : undefined)),
paymentMethod: z
.enum(["cash", "transfer", "card", "check", "other"])
.optional()
.transform((v) => v || undefined),
});
export type FinanceEntryInput = z.infer<typeof financeEntrySchema>;