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:
@@ -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 { FinanceFormSheet } from "./finance-form-sheet";
|
||||||
import {
|
import {
|
||||||
|
type BankAccountOption,
|
||||||
type Customer,
|
type Customer,
|
||||||
type FinanceRow,
|
type FinanceRow,
|
||||||
type FinanceType,
|
type FinanceType,
|
||||||
@@ -76,6 +77,7 @@ import {
|
|||||||
type Props = {
|
type Props = {
|
||||||
entries: FinanceRow[];
|
entries: FinanceRow[];
|
||||||
customers: Customer[];
|
customers: Customer[];
|
||||||
|
bankAccounts: BankAccountOption[];
|
||||||
};
|
};
|
||||||
|
|
||||||
function StatCard({
|
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 [tab, setTab] = useState<FinanceType | "all">("all");
|
||||||
const [search, setSearch] = useState("");
|
const [search, setSearch] = useState("");
|
||||||
const [sorting, setSorting] = useState<SortingState>([]);
|
const [sorting, setSorting] = useState<SortingState>([]);
|
||||||
@@ -398,6 +400,7 @@ export function FinanceClient({ entries, customers }: Props) {
|
|||||||
entry={editing}
|
entry={editing}
|
||||||
defaultType={defaultType}
|
defaultType={defaultType}
|
||||||
customers={customers}
|
customers={customers}
|
||||||
|
bankAccounts={bankAccounts}
|
||||||
onRequestDelete={(e) => {
|
onRequestDelete={(e) => {
|
||||||
setFormOpen(false);
|
setFormOpen(false);
|
||||||
setDeleting(e);
|
setDeleting(e);
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ import {
|
|||||||
} from "@/lib/appwrite/finance-actions";
|
} from "@/lib/appwrite/finance-actions";
|
||||||
import { initialFinanceState } from "@/lib/appwrite/finance-types";
|
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__";
|
const NONE = "__none__";
|
||||||
|
|
||||||
@@ -39,6 +39,7 @@ type Props = {
|
|||||||
entry?: FinanceRow | null;
|
entry?: FinanceRow | null;
|
||||||
defaultType?: FinanceType;
|
defaultType?: FinanceType;
|
||||||
customers: Customer[];
|
customers: Customer[];
|
||||||
|
bankAccounts: BankAccountOption[];
|
||||||
onRequestDelete?: (entry: FinanceRow) => void;
|
onRequestDelete?: (entry: FinanceRow) => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -53,6 +54,7 @@ export function FinanceFormSheet({
|
|||||||
entry,
|
entry,
|
||||||
defaultType = "income",
|
defaultType = "income",
|
||||||
customers,
|
customers,
|
||||||
|
bankAccounts,
|
||||||
onRequestDelete,
|
onRequestDelete,
|
||||||
}: Props) {
|
}: Props) {
|
||||||
const isEdit = Boolean(entry);
|
const isEdit = Boolean(entry);
|
||||||
@@ -83,7 +85,7 @@ export function FinanceFormSheet({
|
|||||||
|
|
||||||
<form
|
<form
|
||||||
action={(fd) => {
|
action={(fd) => {
|
||||||
["customerId", "paymentMethod"].forEach((k) => {
|
["customerId", "paymentMethod", "bankAccountId"].forEach((k) => {
|
||||||
if (fd.get(k) === NONE) fd.set(k, "");
|
if (fd.get(k) === NONE) fd.set(k, "");
|
||||||
});
|
});
|
||||||
formAction(fd);
|
formAction(fd);
|
||||||
@@ -158,21 +160,43 @@ export function FinanceFormSheet({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid gap-2">
|
<div className="grid gap-4 md:grid-cols-2">
|
||||||
<Label htmlFor="customerId">Müşteri (opsiyonel)</Label>
|
<div className="grid gap-2">
|
||||||
<Select name="customerId" defaultValue={entry?.customerId || NONE}>
|
<Label htmlFor="customerId">Müşteri (opsiyonel)</Label>
|
||||||
<SelectTrigger id="customerId">
|
<Select name="customerId" defaultValue={entry?.customerId || NONE}>
|
||||||
<SelectValue placeholder="Yok" />
|
<SelectTrigger id="customerId">
|
||||||
</SelectTrigger>
|
<SelectValue placeholder="Yok" />
|
||||||
<SelectContent>
|
</SelectTrigger>
|
||||||
<SelectItem value={NONE}>Yok</SelectItem>
|
<SelectContent>
|
||||||
{customers.map((c) => (
|
<SelectItem value={NONE}>Yok</SelectItem>
|
||||||
<SelectItem key={c.id} value={c.id}>
|
{customers.map((c) => (
|
||||||
{c.name}
|
<SelectItem key={c.id} value={c.id}>
|
||||||
</SelectItem>
|
{c.name}
|
||||||
))}
|
</SelectItem>
|
||||||
</SelectContent>
|
))}
|
||||||
</Select>
|
</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>
|
||||||
|
|
||||||
<div className="grid gap-2">
|
<div className="grid gap-2">
|
||||||
|
|||||||
@@ -11,9 +11,12 @@ export type FinanceRow = {
|
|||||||
customerName: string;
|
customerName: string;
|
||||||
paymentMethod: PaymentMethod;
|
paymentMethod: PaymentMethod;
|
||||||
invoiceId: string;
|
invoiceId: string;
|
||||||
|
bankAccountId: string;
|
||||||
|
bankAccountLabel: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type Customer = { id: string; name: string };
|
export type Customer = { id: string; name: string };
|
||||||
|
export type BankAccountOption = { id: string; label: string };
|
||||||
|
|
||||||
export const TYPE_LABEL: Record<FinanceType, string> = {
|
export const TYPE_LABEL: Record<FinanceType, string> = {
|
||||||
income: "Gelir",
|
income: "Gelir",
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import type { Metadata } from "next";
|
import type { Metadata } from "next";
|
||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
|
|
||||||
|
import { listBankAccounts } from "@/lib/appwrite/bank-account-queries";
|
||||||
import { listCustomers } from "@/lib/appwrite/customer-queries";
|
import { listCustomers } from "@/lib/appwrite/customer-queries";
|
||||||
import { listFinanceEntries } from "@/lib/appwrite/finance-queries";
|
import { listFinanceEntries } from "@/lib/appwrite/finance-queries";
|
||||||
import { requireTenant } from "@/lib/appwrite/tenant-guard";
|
import { requireTenant } from "@/lib/appwrite/tenant-guard";
|
||||||
@@ -18,12 +19,16 @@ export default async function FinancePage() {
|
|||||||
redirect("/onboarding");
|
redirect("/onboarding");
|
||||||
}
|
}
|
||||||
|
|
||||||
const [entries, customers] = await Promise.all([
|
const [entries, customers, bankAccounts] = await Promise.all([
|
||||||
listFinanceEntries(ctx.tenantId),
|
listFinanceEntries(ctx.tenantId),
|
||||||
listCustomers(ctx.tenantId),
|
listCustomers(ctx.tenantId),
|
||||||
|
listBankAccounts(ctx.tenantId),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const customerMap = new Map(customers.map((c) => [c.$id, c.name]));
|
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 (
|
return (
|
||||||
<div className="flex-1 space-y-6 px-6 pt-0">
|
<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) ?? "" : "",
|
customerName: e.customerId ? customerMap.get(e.customerId) ?? "" : "",
|
||||||
paymentMethod: e.paymentMethod ?? "",
|
paymentMethod: e.paymentMethod ?? "",
|
||||||
invoiceId: e.invoiceId ?? "",
|
invoiceId: e.invoiceId ?? "",
|
||||||
|
bankAccountId: e.bankAccountId ?? "",
|
||||||
|
bankAccountLabel: e.bankAccountId ? bankMap.get(e.bankAccountId) ?? "" : "",
|
||||||
}))}
|
}))}
|
||||||
customers={customers.map((c) => ({ id: c.$id, name: c.name }))}
|
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>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -85,6 +85,16 @@ const navGroups = [
|
|||||||
url: "/finance",
|
url: "/finance",
|
||||||
icon: Wallet,
|
icon: Wallet,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
title: "Bankalar",
|
||||||
|
url: "/finance/banks",
|
||||||
|
icon: Briefcase,
|
||||||
|
items: [
|
||||||
|
{ title: "Banka hesapları", url: "/finance/banks" },
|
||||||
|
{ title: "Krediler", url: "/finance/loans" },
|
||||||
|
{ title: "Kredi kartları", url: "/finance/cards" },
|
||||||
|
],
|
||||||
|
},
|
||||||
{
|
{
|
||||||
title: "Faturalar",
|
title: "Faturalar",
|
||||||
url: "/invoices",
|
url: "/invoices",
|
||||||
|
|||||||
@@ -0,0 +1,244 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { AppwriteException, ID, Permission, Query, Role } from "node-appwrite";
|
||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
import { logAudit } from "./audit";
|
||||||
|
import { DATABASE_ID, TABLES, type BankAccount } from "./schema";
|
||||||
|
import { createAdminClient } from "./server";
|
||||||
|
import { requireTenant } from "./tenant-guard";
|
||||||
|
import type { BankAccountActionState } from "./bank-account-types";
|
||||||
|
import { bankAccountSchema } from "@/lib/validation/bank-accounts";
|
||||||
|
|
||||||
|
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 {
|
||||||
|
bankName: String(formData.get("bankName") ?? "").trim(),
|
||||||
|
accountName: String(formData.get("accountName") ?? "").trim(),
|
||||||
|
iban: String(formData.get("iban") ?? "").trim(),
|
||||||
|
openingBalance: String(formData.get("openingBalance") ?? "0"),
|
||||||
|
notes: String(formData.get("notes") ?? "").trim(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createBankAccountAction(
|
||||||
|
_prev: BankAccountActionState,
|
||||||
|
formData: FormData,
|
||||||
|
): Promise<BankAccountActionState> {
|
||||||
|
let ctx;
|
||||||
|
try {
|
||||||
|
ctx = await requireTenant();
|
||||||
|
} catch {
|
||||||
|
return { ok: false, error: "Yetkiniz yok." };
|
||||||
|
}
|
||||||
|
|
||||||
|
const parsed = bankAccountSchema.safeParse(pickFormFields(formData));
|
||||||
|
if (!parsed.success) {
|
||||||
|
return { ok: false, error: "Form geçersiz.", fieldErrors: flattenErrors(parsed.error) };
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { tablesDB } = createAdminClient();
|
||||||
|
const row = await tablesDB.createRow(
|
||||||
|
DATABASE_ID,
|
||||||
|
TABLES.bankAccounts,
|
||||||
|
ID.unique(),
|
||||||
|
{
|
||||||
|
tenantId: ctx.tenantId,
|
||||||
|
createdBy: ctx.user.id,
|
||||||
|
...parsed.data,
|
||||||
|
},
|
||||||
|
teamRowPermissions(ctx.tenantId),
|
||||||
|
);
|
||||||
|
|
||||||
|
await logAudit({
|
||||||
|
tenantId: ctx.tenantId,
|
||||||
|
userId: ctx.user.id,
|
||||||
|
action: "create",
|
||||||
|
entityType: "bank_account",
|
||||||
|
entityId: row.$id,
|
||||||
|
changes: parsed.data,
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
return { ok: false, error: appwriteError(e) };
|
||||||
|
}
|
||||||
|
|
||||||
|
revalidatePath("/finance/banks");
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateBankAccountAction(
|
||||||
|
_prev: BankAccountActionState,
|
||||||
|
formData: FormData,
|
||||||
|
): Promise<BankAccountActionState> {
|
||||||
|
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 = bankAccountSchema.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.bankAccounts,
|
||||||
|
id,
|
||||||
|
)) as unknown as BankAccount;
|
||||||
|
if (existing.tenantId !== ctx.tenantId) {
|
||||||
|
return { ok: false, error: "Erişim engellendi." };
|
||||||
|
}
|
||||||
|
|
||||||
|
await tablesDB.updateRow(DATABASE_ID, TABLES.bankAccounts, id, parsed.data);
|
||||||
|
|
||||||
|
await logAudit({
|
||||||
|
tenantId: ctx.tenantId,
|
||||||
|
userId: ctx.user.id,
|
||||||
|
action: "update",
|
||||||
|
entityType: "bank_account",
|
||||||
|
entityId: id,
|
||||||
|
changes: parsed.data,
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
return { ok: false, error: appwriteError(e) };
|
||||||
|
}
|
||||||
|
|
||||||
|
revalidatePath("/finance/banks");
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function archiveBankAccountAction(
|
||||||
|
formData: FormData,
|
||||||
|
): Promise<BankAccountActionState> {
|
||||||
|
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.bankAccounts,
|
||||||
|
id,
|
||||||
|
)) as unknown as BankAccount;
|
||||||
|
if (existing.tenantId !== ctx.tenantId) {
|
||||||
|
return { ok: false, error: "Erişim engellendi." };
|
||||||
|
}
|
||||||
|
|
||||||
|
const newArchivedState = !existing.archived;
|
||||||
|
await tablesDB.updateRow(DATABASE_ID, TABLES.bankAccounts, id, {
|
||||||
|
archived: newArchivedState,
|
||||||
|
});
|
||||||
|
|
||||||
|
await logAudit({
|
||||||
|
tenantId: ctx.tenantId,
|
||||||
|
userId: ctx.user.id,
|
||||||
|
action: "update",
|
||||||
|
entityType: "bank_account",
|
||||||
|
entityId: id,
|
||||||
|
changes: { archived: newArchivedState },
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
return { ok: false, error: appwriteError(e) };
|
||||||
|
}
|
||||||
|
|
||||||
|
revalidatePath("/finance/banks");
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteBankAccountAction(
|
||||||
|
formData: FormData,
|
||||||
|
): Promise<BankAccountActionState> {
|
||||||
|
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.bankAccounts,
|
||||||
|
id,
|
||||||
|
)) as unknown as BankAccount;
|
||||||
|
if (existing.tenantId !== ctx.tenantId) {
|
||||||
|
return { ok: false, error: "Erişim engellendi." };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Block delete if any finance_entry still references this account.
|
||||||
|
const linked = await tablesDB.listRows({
|
||||||
|
databaseId: DATABASE_ID,
|
||||||
|
tableId: TABLES.financeEntries,
|
||||||
|
queries: [
|
||||||
|
Query.equal("tenantId", ctx.tenantId),
|
||||||
|
Query.equal("bankAccountId", id),
|
||||||
|
Query.limit(1),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
if (linked.rows.length > 0) {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
error:
|
||||||
|
"Bu hesaba bağlı finans hareketleri var. Önce hesabı arşivleyin veya hareketleri başka bir hesaba taşıyın.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
await tablesDB.deleteRow(DATABASE_ID, TABLES.bankAccounts, id);
|
||||||
|
|
||||||
|
await logAudit({
|
||||||
|
tenantId: ctx.tenantId,
|
||||||
|
userId: ctx.user.id,
|
||||||
|
action: "delete",
|
||||||
|
entityType: "bank_account",
|
||||||
|
entityId: id,
|
||||||
|
changes: { bankName: existing.bankName, accountName: existing.accountName },
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
return { ok: false, error: appwriteError(e) };
|
||||||
|
}
|
||||||
|
|
||||||
|
revalidatePath("/finance/banks");
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
import "server-only";
|
||||||
|
|
||||||
|
import { Query } from "node-appwrite";
|
||||||
|
|
||||||
|
import { createAdminClient } from "./server";
|
||||||
|
import {
|
||||||
|
DATABASE_ID,
|
||||||
|
TABLES,
|
||||||
|
type BankAccount,
|
||||||
|
type FinanceEntry,
|
||||||
|
} from "./schema";
|
||||||
|
|
||||||
|
export async function listBankAccounts(tenantId: string): Promise<BankAccount[]> {
|
||||||
|
try {
|
||||||
|
const { tablesDB } = createAdminClient();
|
||||||
|
const result = await tablesDB.listRows({
|
||||||
|
databaseId: DATABASE_ID,
|
||||||
|
tableId: TABLES.bankAccounts,
|
||||||
|
queries: [
|
||||||
|
Query.equal("tenantId", tenantId),
|
||||||
|
Query.orderAsc("bankName"),
|
||||||
|
Query.limit(200),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
return result.rows as unknown as BankAccount[];
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Computes a current balance for each account: openingBalance + Σ(income/receivable) − Σ(expense/debt).
|
||||||
|
*/
|
||||||
|
export async function getBankAccountBalances(
|
||||||
|
tenantId: string,
|
||||||
|
): Promise<Map<string, number>> {
|
||||||
|
const balances = new Map<string, number>();
|
||||||
|
try {
|
||||||
|
const { tablesDB } = createAdminClient();
|
||||||
|
const accounts = await tablesDB.listRows({
|
||||||
|
databaseId: DATABASE_ID,
|
||||||
|
tableId: TABLES.bankAccounts,
|
||||||
|
queries: [Query.equal("tenantId", tenantId), Query.limit(200)],
|
||||||
|
});
|
||||||
|
for (const a of accounts.rows as unknown as BankAccount[]) {
|
||||||
|
balances.set(a.$id, a.openingBalance ?? 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
const entries = await tablesDB.listRows({
|
||||||
|
databaseId: DATABASE_ID,
|
||||||
|
tableId: TABLES.financeEntries,
|
||||||
|
queries: [
|
||||||
|
Query.equal("tenantId", tenantId),
|
||||||
|
Query.isNotNull("bankAccountId"),
|
||||||
|
Query.limit(5000),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
for (const e of entries.rows as unknown as FinanceEntry[]) {
|
||||||
|
if (!e.bankAccountId) continue;
|
||||||
|
const cur = balances.get(e.bankAccountId);
|
||||||
|
if (cur === undefined) continue;
|
||||||
|
if (e.type === "income") balances.set(e.bankAccountId, cur + e.amount);
|
||||||
|
else if (e.type === "expense") balances.set(e.bankAccountId, cur - e.amount);
|
||||||
|
// debt/receivable don't affect cash balance
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
return balances;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listEntriesForAccount(
|
||||||
|
tenantId: string,
|
||||||
|
bankAccountId: string,
|
||||||
|
limit = 25,
|
||||||
|
): Promise<FinanceEntry[]> {
|
||||||
|
try {
|
||||||
|
const { tablesDB } = createAdminClient();
|
||||||
|
const result = await tablesDB.listRows({
|
||||||
|
databaseId: DATABASE_ID,
|
||||||
|
tableId: TABLES.financeEntries,
|
||||||
|
queries: [
|
||||||
|
Query.equal("tenantId", tenantId),
|
||||||
|
Query.equal("bankAccountId", bankAccountId),
|
||||||
|
Query.orderDesc("date"),
|
||||||
|
Query.limit(limit),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
return result.rows as unknown as FinanceEntry[];
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
export type BankAccountActionState = {
|
||||||
|
ok: boolean;
|
||||||
|
error?: string;
|
||||||
|
fieldErrors?: Record<string, string>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const initialBankAccountState: BankAccountActionState = { ok: false };
|
||||||
@@ -49,6 +49,7 @@ function pickFormFields(formData: FormData) {
|
|||||||
| "check"
|
| "check"
|
||||||
| "other"
|
| "other"
|
||||||
| null,
|
| null,
|
||||||
|
bankAccountId: String(formData.get("bankAccountId") ?? ""),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ export const TABLES = {
|
|||||||
invoiceItems: "invoice_items",
|
invoiceItems: "invoice_items",
|
||||||
auditLogs: "audit_logs",
|
auditLogs: "audit_logs",
|
||||||
inviteLinks: "invite_links",
|
inviteLinks: "invite_links",
|
||||||
|
bankAccounts: "bank_accounts",
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
export type TableId = (typeof TABLES)[keyof typeof TABLES];
|
export type TableId = (typeof TABLES)[keyof typeof TABLES];
|
||||||
@@ -133,6 +134,7 @@ export interface FinanceEntry extends Row {
|
|||||||
customerId?: string;
|
customerId?: string;
|
||||||
invoiceId?: string;
|
invoiceId?: string;
|
||||||
paymentMethod?: PaymentMethod;
|
paymentMethod?: PaymentMethod;
|
||||||
|
bankAccountId?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type InvoiceStatus = "draft" | "sent" | "paid" | "overdue" | "cancelled";
|
export type InvoiceStatus = "draft" | "sent" | "paid" | "overdue" | "cancelled";
|
||||||
@@ -175,6 +177,17 @@ export interface AuditLog extends Row {
|
|||||||
userAgent?: string;
|
userAgent?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface BankAccount extends Row {
|
||||||
|
tenantId: string;
|
||||||
|
createdBy: string;
|
||||||
|
bankName: string;
|
||||||
|
accountName: string;
|
||||||
|
iban?: string;
|
||||||
|
openingBalance?: number;
|
||||||
|
notes?: string;
|
||||||
|
archived?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
export type InviteRole = "admin" | "member";
|
export type InviteRole = "admin" | "member";
|
||||||
export type InviteStatus = "pending" | "accepted" | "cancelled" | "expired";
|
export type InviteStatus = "pending" | "accepted" | "cancelled" | "expired";
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
export const bankAccountSchema = z.object({
|
||||||
|
bankName: z.string().trim().min(1, "Banka adı zorunlu.").max(100),
|
||||||
|
accountName: z.string().trim().min(1, "Hesap adı zorunlu.").max(100),
|
||||||
|
iban: z
|
||||||
|
.string()
|
||||||
|
.trim()
|
||||||
|
.max(50)
|
||||||
|
.optional()
|
||||||
|
.transform((v) => (v ? v.replace(/\s+/g, "").toUpperCase() : undefined)),
|
||||||
|
openingBalance: z
|
||||||
|
.union([z.number(), z.string()])
|
||||||
|
.optional()
|
||||||
|
.transform((v) => {
|
||||||
|
if (v === undefined || v === "") return 0;
|
||||||
|
const n = typeof v === "string" ? Number(v.replace(",", ".")) : v;
|
||||||
|
return Number.isFinite(n) ? n : 0;
|
||||||
|
}),
|
||||||
|
notes: z
|
||||||
|
.string()
|
||||||
|
.trim()
|
||||||
|
.max(500)
|
||||||
|
.optional()
|
||||||
|
.transform((v) => (v ? v : undefined)),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type BankAccountInput = z.infer<typeof bankAccountSchema>;
|
||||||
@@ -14,6 +14,7 @@ export const financeEntrySchema = z.object({
|
|||||||
.enum(["cash", "transfer", "card", "check", "other"])
|
.enum(["cash", "transfer", "card", "check", "other"])
|
||||||
.optional()
|
.optional()
|
||||||
.transform((v) => v || undefined),
|
.transform((v) => v || undefined),
|
||||||
|
bankAccountId: z.string().optional().transform((v) => (v ? v : undefined)),
|
||||||
});
|
});
|
||||||
|
|
||||||
export type FinanceEntryInput = z.infer<typeof financeEntrySchema>;
|
export type FinanceEntryInput = z.infer<typeof financeEntrySchema>;
|
||||||
|
|||||||
Reference in New Issue
Block a user