feat(banking A): bank accounts module + finance integration

First of 3-step banking expansion. Banks tracked separately from
customer/supplier debts so we can compute real cash position later.

Schema:
- New bank_accounts table: bankName, accountName, iban, openingBalance,
  notes, archived. Indexes on (tenantId, archived).
- New column finance_entries.bankAccountId (FK, optional). Index on
  (tenantId, bankAccountId).
- schema.ts: TABLES.bankAccounts, BankAccount type, FinanceEntry gains
  bankAccountId.

Server side:
- lib/validation/bank-accounts.ts (Zod): IBAN normalized to upper-case
  no-spaces; openingBalance defaults to 0.
- lib/appwrite/bank-account-actions.ts: create/update/archive(toggle)/
  delete with audit. Delete refuses if any finance_entry still references
  the account; archive toggle replaces it for safe disable.
- lib/appwrite/bank-account-queries.ts:
  * listBankAccounts
  * getBankAccountBalances — computes opening + Σ(income) − Σ(expense)
    per account by scanning up to 5000 entries with bankAccountId set.
    Pure cash flow; debt/receivable don't move balance.
  * listEntriesForAccount

UI:
- /finance/banks server page renders BanksClient with computed balances.
- BanksClient: card grid for active accounts, collapsed details for
  archived. Sum card on top showing total active balance (color-coded by
  sign). Each card shows bank, account name, formatted IBAN, current
  balance + opening (if drifted). Dropdown: Düzenle / Arşivle / Sil.
- BankFormSheet: bank/account/IBAN/openingBalance/notes form.
- Finance form gets a bank-account Select (sentinel-stripped). Existing
  finance entries get a 'bankAccountLabel' subtitle in their row.

Sidebar: Finans group expanded with Bankalar submenu (Banka hesapları
/ Krediler / Kredi kartları). The latter two land in B and C.
This commit is contained in:
kovakmedya
2026-04-30 07:22:51 +03:00
parent c848531326
commit 7b6be623ae
16 changed files with 972 additions and 19 deletions
@@ -0,0 +1,159 @@
"use client";
import { useActionState, useEffect } from "react";
import { Loader2, Save } 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 {
Sheet,
SheetContent,
SheetDescription,
SheetFooter,
SheetHeader,
SheetTitle,
} from "@/components/ui/sheet";
import { Textarea } from "@/components/ui/textarea";
import {
createBankAccountAction,
updateBankAccountAction,
} from "@/lib/appwrite/bank-account-actions";
import { initialBankAccountState } from "@/lib/appwrite/bank-account-types";
import type { BankAccountRow } from "./types";
type Props = {
open: boolean;
onOpenChange: (v: boolean) => void;
account?: BankAccountRow | null;
};
export function BankFormSheet({ open, onOpenChange, account }: Props) {
const isEdit = Boolean(account);
const action = isEdit ? updateBankAccountAction : createBankAccountAction;
const [state, formAction, isPending] = useActionState(action, initialBankAccountState);
useEffect(() => {
if (state.ok) {
toast.success(isEdit ? "Hesap güncellendi." : "Hesap eklendi.");
onOpenChange(false);
} else if (state.error) {
toast.error(state.error);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [state]);
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 ? "Hesabı düzenle" : "Yeni banka hesabı"}</SheetTitle>
<SheetDescription>
Açılış bakiyesi sonradan değiştirilirse bütün hareketler aynı kalır, sadece toplam
kayar.
</SheetDescription>
</SheetHeader>
<form action={formAction} className="flex flex-1 flex-col">
{isEdit && account && <input type="hidden" name="id" value={account.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="bankName">Banka *</Label>
<Input
id="bankName"
name="bankName"
defaultValue={account?.bankName ?? ""}
placeholder="Örn. Garanti BBVA"
required
/>
{state.fieldErrors?.bankName && (
<p className="text-destructive text-xs">{state.fieldErrors.bankName}</p>
)}
</div>
<div className="grid gap-2">
<Label htmlFor="accountName">Hesap adı *</Label>
<Input
id="accountName"
name="accountName"
defaultValue={account?.accountName ?? ""}
placeholder="Örn. Şirket TL Vadesiz"
required
/>
{state.fieldErrors?.accountName && (
<p className="text-destructive text-xs">{state.fieldErrors.accountName}</p>
)}
</div>
</div>
<div className="grid gap-2">
<Label htmlFor="iban">IBAN</Label>
<Input
id="iban"
name="iban"
defaultValue={account?.iban ?? ""}
placeholder="TR.. .... .... .... .... .... .."
style={{ fontFamily: "monospace", textTransform: "uppercase" }}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="openingBalance">Açılış bakiyesi ()</Label>
<Input
id="openingBalance"
name="openingBalance"
type="number"
step="0.01"
defaultValue={account?.openingBalance ?? 0}
placeholder="0.00"
/>
<p className="text-muted-foreground text-xs">
Bu hesabı sisteme eklediğinizdeki bakiye. Sonraki hareketler bu rakamın üstüne eklenir.
</p>
</div>
<div className="grid gap-2">
<Label htmlFor="notes">Notlar</Label>
<Textarea
id="notes"
name="notes"
rows={3}
defaultValue={account?.notes ?? ""}
placeholder="Şube, yetkili, müşteri no, vb."
/>
</div>
</div>
<SheetFooter className="border-t bg-muted/30 px-6 py-4">
<div className="flex w-full justify-end 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>
</SheetFooter>
</form>
</SheetContent>
</Sheet>
);
}
@@ -0,0 +1,292 @@
"use client";
import { useState, useTransition } from "react";
import {
Archive,
ArchiveRestore,
Building2,
Loader2,
MoreHorizontal,
Pencil,
Plus,
Trash2,
} 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,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
archiveBankAccountAction,
deleteBankAccountAction,
} from "@/lib/appwrite/bank-account-actions";
import { formatTRY } from "@/lib/format";
import { cn } from "@/lib/utils";
import { BankFormSheet } from "./bank-form-sheet";
import type { BankAccountRow } from "./types";
type Props = { accounts: BankAccountRow[] };
export function BanksClient({ accounts }: Props) {
const [formOpen, setFormOpen] = useState(false);
const [editing, setEditing] = useState<BankAccountRow | null>(null);
const [deleting, setDeleting] = useState<BankAccountRow | null>(null);
const [busy, startTransition] = useTransition();
const active = accounts.filter((a) => !a.archived);
const archived = accounts.filter((a) => a.archived);
const totalBalance = active.reduce((s, a) => s + a.balance, 0);
const toggleArchive = (acc: BankAccountRow) => {
startTransition(async () => {
const fd = new FormData();
fd.set("id", acc.id);
const result = await archiveBankAccountAction(fd);
if (result.ok) {
toast.success(acc.archived ? "Hesap geri açıldı." : "Hesap arşivlendi.");
} else {
toast.error(result.error ?? "İşlem başarısız.");
}
});
};
const handleDelete = () => {
if (!deleting) return;
startTransition(async () => {
const fd = new FormData();
fd.set("id", deleting.id);
const result = await deleteBankAccountAction(fd);
if (result.ok) {
toast.success("Hesap silindi.");
setDeleting(null);
} else {
toast.error(result.error ?? "Silme başarısız.");
}
});
};
return (
<div className="space-y-6">
<div className="flex items-center justify-between gap-3">
<Card className="flex-1">
<CardContent className="p-4">
<p className="text-muted-foreground text-xs">Toplam bakiye (aktif hesaplar)</p>
<p
className={cn(
"mt-1 text-2xl font-semibold tabular-nums",
totalBalance >= 0 ? "text-emerald-600 dark:text-emerald-400" : "text-red-600 dark:text-red-400",
)}
>
{formatTRY(totalBalance)}
</p>
</CardContent>
</Card>
<Button
onClick={() => {
setEditing(null);
setFormOpen(true);
}}
>
<Plus className="size-4" />
Yeni hesap
</Button>
</div>
{active.length === 0 && archived.length === 0 ? (
<Card>
<CardContent className="flex flex-col items-center gap-2 py-12 text-center">
<Building2 className="text-muted-foreground size-8" />
<p className="text-sm">Henüz banka hesabı eklenmemiş.</p>
<Button
variant="outline"
size="sm"
onClick={() => {
setEditing(null);
setFormOpen(true);
}}
>
<Plus className="size-3.5" />
İlk hesabı ekle
</Button>
</CardContent>
</Card>
) : (
<>
<div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
{active.map((a) => (
<AccountCard
key={a.id}
account={a}
onEdit={() => {
setEditing(a);
setFormOpen(true);
}}
onArchiveToggle={() => toggleArchive(a)}
onDelete={() => setDeleting(a)}
busy={busy}
/>
))}
</div>
{archived.length > 0 && (
<details className="group">
<summary className="text-muted-foreground hover:text-foreground cursor-pointer text-sm">
Arşivlenmiş hesaplar ({archived.length})
</summary>
<div className="mt-4 grid gap-4 md:grid-cols-2 xl:grid-cols-3">
{archived.map((a) => (
<AccountCard
key={a.id}
account={a}
onEdit={() => {
setEditing(a);
setFormOpen(true);
}}
onArchiveToggle={() => toggleArchive(a)}
onDelete={() => setDeleting(a)}
busy={busy}
/>
))}
</div>
</details>
)}
</>
)}
<BankFormSheet
open={formOpen}
onOpenChange={(v) => {
setFormOpen(v);
if (!v) setEditing(null);
}}
account={editing}
/>
<Dialog open={Boolean(deleting)} onOpenChange={(v) => !v && setDeleting(null)}>
<DialogContent>
<DialogHeader>
<DialogTitle>Hesabı sil</DialogTitle>
<DialogDescription>
<strong>{deleting?.bankName} {deleting?.accountName}</strong> kalıcı olarak silinecek.
Bağlı finans hareketi varsa silme reddedilir; o durumda arşivlemeyi tercih edin.
</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>
</div>
);
}
function AccountCard({
account,
onEdit,
onArchiveToggle,
onDelete,
busy,
}: {
account: BankAccountRow;
onEdit: () => void;
onArchiveToggle: () => void;
onDelete: () => void;
busy: boolean;
}) {
const positive = account.balance >= 0;
return (
<Card className={cn(account.archived && "opacity-60")}>
<CardContent className="space-y-3 p-4">
<div className="flex items-start justify-between gap-2">
<div className="min-w-0">
<div className="flex items-center gap-2">
<Building2 className="text-muted-foreground size-4 shrink-0" />
<h3 className="truncate font-medium">{account.bankName}</h3>
{account.archived && (
<Badge variant="outline" className="text-[10px]">
Arşivli
</Badge>
)}
</div>
<p className="text-muted-foreground mt-0.5 truncate text-sm">{account.accountName}</p>
{account.iban && (
<p className="text-muted-foreground mt-1 truncate font-mono text-[11px]">
{account.iban.replace(/(.{4})/g, "$1 ").trim()}
</p>
)}
</div>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="size-8 shrink-0" disabled={busy}>
<MoreHorizontal className="size-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={onEdit}>
<Pencil className="size-3.5" />
Düzenle
</DropdownMenuItem>
<DropdownMenuItem onClick={onArchiveToggle}>
{account.archived ? (
<>
<ArchiveRestore className="size-3.5" />
Arşivden çıkar
</>
) : (
<>
<Archive className="size-3.5" />
Arşivle
</>
)}
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem variant="destructive" onClick={onDelete}>
<Trash2 className="size-3.5" />
Sil
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
<div>
<p className="text-muted-foreground text-xs">Güncel bakiye</p>
<p
className={cn(
"text-xl font-semibold tabular-nums",
positive ? "text-emerald-600 dark:text-emerald-400" : "text-red-600 dark:text-red-400",
)}
>
{formatTRY(account.balance)}
</p>
{account.balance !== account.openingBalance && (
<p className="text-muted-foreground mt-0.5 text-[11px]">
Açılış: {formatTRY(account.openingBalance)}
</p>
)}
</div>
</CardContent>
</Card>
);
}
@@ -0,0 +1,10 @@
export type BankAccountRow = {
id: string;
bankName: string;
accountName: string;
iban: string;
openingBalance: number;
notes: string;
archived: boolean;
balance: number;
};
@@ -0,0 +1,52 @@
import type { Metadata } from "next";
import { redirect } from "next/navigation";
import {
getBankAccountBalances,
listBankAccounts,
} from "@/lib/appwrite/bank-account-queries";
import { requireTenant } from "@/lib/appwrite/tenant-guard";
import { BanksClient } from "./components/banks-client";
export const metadata: Metadata = {
title: "İşletmem — Banka hesapları",
};
export default async function BanksPage() {
let ctx;
try {
ctx = await requireTenant();
} catch {
redirect("/onboarding");
}
const [accounts, balances] = await Promise.all([
listBankAccounts(ctx.tenantId),
getBankAccountBalances(ctx.tenantId),
]);
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">Banka hesapları</h1>
<p className="text-muted-foreground text-sm">
İşletmenize ait banka hesaplarını ve güncel bakiyelerini takip edin.
</p>
</div>
<BanksClient
accounts={accounts.map((a) => ({
id: a.$id,
bankName: a.bankName,
accountName: a.accountName,
iban: a.iban ?? "",
openingBalance: a.openingBalance ?? 0,
notes: a.notes ?? "",
archived: Boolean(a.archived),
balance: balances.get(a.$id) ?? a.openingBalance ?? 0,
}))}
/>
</div>
);
}
@@ -65,6 +65,7 @@ import { cn } from "@/lib/utils";
import { FinanceFormSheet } from "./finance-form-sheet";
import {
type BankAccountOption,
type Customer,
type FinanceRow,
type FinanceType,
@@ -76,6 +77,7 @@ import {
type Props = {
entries: FinanceRow[];
customers: Customer[];
bankAccounts: BankAccountOption[];
};
function StatCard({
@@ -109,7 +111,7 @@ function StatCard({
);
}
export function FinanceClient({ entries, customers }: Props) {
export function FinanceClient({ entries, customers, bankAccounts }: Props) {
const [tab, setTab] = useState<FinanceType | "all">("all");
const [search, setSearch] = useState("");
const [sorting, setSorting] = useState<SortingState>([]);
@@ -398,6 +400,7 @@ export function FinanceClient({ entries, customers }: Props) {
entry={editing}
defaultType={defaultType}
customers={customers}
bankAccounts={bankAccounts}
onRequestDelete={(e) => {
setFormOpen(false);
setDeleting(e);
@@ -29,7 +29,7 @@ import {
} from "@/lib/appwrite/finance-actions";
import { initialFinanceState } from "@/lib/appwrite/finance-types";
import type { Customer, FinanceRow, FinanceType } from "./types";
import type { BankAccountOption, Customer, FinanceRow, FinanceType } from "./types";
const NONE = "__none__";
@@ -39,6 +39,7 @@ type Props = {
entry?: FinanceRow | null;
defaultType?: FinanceType;
customers: Customer[];
bankAccounts: BankAccountOption[];
onRequestDelete?: (entry: FinanceRow) => void;
};
@@ -53,6 +54,7 @@ export function FinanceFormSheet({
entry,
defaultType = "income",
customers,
bankAccounts,
onRequestDelete,
}: Props) {
const isEdit = Boolean(entry);
@@ -83,7 +85,7 @@ export function FinanceFormSheet({
<form
action={(fd) => {
["customerId", "paymentMethod"].forEach((k) => {
["customerId", "paymentMethod", "bankAccountId"].forEach((k) => {
if (fd.get(k) === NONE) fd.set(k, "");
});
formAction(fd);
@@ -158,21 +160,43 @@ export function FinanceFormSheet({
</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 className="grid gap-4 md:grid-cols-2">
<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="bankAccountId">Banka hesabı</Label>
<Select
name="bankAccountId"
defaultValue={entry?.bankAccountId || NONE}
disabled={bankAccounts.length === 0}
>
<SelectTrigger id="bankAccountId">
<SelectValue placeholder={bankAccounts.length === 0 ? "Önce hesap ekleyin" : "Yok"} />
</SelectTrigger>
<SelectContent>
<SelectItem value={NONE}>Yok</SelectItem>
{bankAccounts.map((b) => (
<SelectItem key={b.id} value={b.id}>
{b.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
<div className="grid gap-2">
@@ -11,9 +11,12 @@ export type FinanceRow = {
customerName: string;
paymentMethod: PaymentMethod;
invoiceId: string;
bankAccountId: string;
bankAccountLabel: string;
};
export type Customer = { id: string; name: string };
export type BankAccountOption = { id: string; label: string };
export const TYPE_LABEL: Record<FinanceType, string> = {
income: "Gelir",
+14 -1
View File
@@ -1,6 +1,7 @@
import type { Metadata } from "next";
import { redirect } from "next/navigation";
import { listBankAccounts } from "@/lib/appwrite/bank-account-queries";
import { listCustomers } from "@/lib/appwrite/customer-queries";
import { listFinanceEntries } from "@/lib/appwrite/finance-queries";
import { requireTenant } from "@/lib/appwrite/tenant-guard";
@@ -18,12 +19,16 @@ export default async function FinancePage() {
redirect("/onboarding");
}
const [entries, customers] = await Promise.all([
const [entries, customers, bankAccounts] = await Promise.all([
listFinanceEntries(ctx.tenantId),
listCustomers(ctx.tenantId),
listBankAccounts(ctx.tenantId),
]);
const customerMap = new Map(customers.map((c) => [c.$id, c.name]));
const bankMap = new Map(
bankAccounts.map((b) => [b.$id, `${b.bankName}${b.accountName}`]),
);
return (
<div className="flex-1 space-y-6 px-6 pt-0">
@@ -46,8 +51,16 @@ export default async function FinancePage() {
customerName: e.customerId ? customerMap.get(e.customerId) ?? "" : "",
paymentMethod: e.paymentMethod ?? "",
invoiceId: e.invoiceId ?? "",
bankAccountId: e.bankAccountId ?? "",
bankAccountLabel: e.bankAccountId ? bankMap.get(e.bankAccountId) ?? "" : "",
}))}
customers={customers.map((c) => ({ id: c.$id, name: c.name }))}
bankAccounts={bankAccounts
.filter((b) => !b.archived)
.map((b) => ({
id: b.$id,
label: `${b.bankName}${b.accountName}`,
}))}
/>
</div>
);