feat(invoices): full invoice + line items module
The most complex module. Two-table model: invoices (header) +
invoice_items (lines). Auto-numbering via tenant_settings.invoiceCounter,
auto-totals on item changes.
Schema/validation:
- lib/validation/invoices.ts: invoiceSchema (header) + invoiceItemSchema
(line). Both coerce comma decimals.
- lib/appwrite/invoice-actions.ts:
* createInvoiceAction — fetches tenant_settings, increments
invoiceCounter, formats number as '{prefix}-{year}-{0000}',
persists totals as 0/0/0 (recomputed when items added).
* updateInvoiceAction / deleteInvoiceAction — header CRUD; delete
cascades to remove all items first then header.
* addInvoiceItemAction / updateInvoiceItemAction /
deleteInvoiceItemAction — line CRUD. Each computes lineTotal
(qty*unit + vat) and triggers recomputeTotals(invoiceId) which
re-sums all items and updates the header subtotal/vatTotal/total.
All audit-logged.
Queries:
- listInvoices, getInvoice (with tenant cross-check), listInvoiceItems.
UI:
- /invoices index: 4 stat cards (Toplam / Tahsil edildi / Bekleyen /
Gecikmiş), table with overdue-aware due date coloring, status badges,
number is a Link to detail.
- InvoiceFormSheet: customer + dates (default issue=today, due=+30d) +
status + notes. After create, redirects to /invoices/[id] for adding
items.
- /invoices/[id] detail: header strip with status, dates, customer name;
print/edit/delete actions; items editor card; subtotal/VAT/total card;
notes card.
- InvoiceItemsEditor: rows are clickable to edit, X button to delete.
ItemFormSheet for add/edit (description + qty + unitPrice + VAT %).
Print is just window.print() for now — relies on browser dialog. Detail
page deliberately uses tabular-nums for amounts.
This commit is contained in:
@@ -0,0 +1,95 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useTransition } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Loader2, Pencil, Printer, Trash2 } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { deleteInvoiceAction } from "@/lib/appwrite/invoice-actions";
|
||||
|
||||
import { InvoiceFormSheet } from "../../components/invoice-form-sheet";
|
||||
import type { Customer, InvoiceRow } from "../../components/types";
|
||||
|
||||
type Props = { invoice: InvoiceRow; customers: Customer[] };
|
||||
|
||||
export function InvoiceHeaderActions({ invoice, customers }: Props) {
|
||||
const router = useRouter();
|
||||
const [editOpen, setEditOpen] = useState(false);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const [busy, startTransition] = useTransition();
|
||||
|
||||
const handleDelete = () => {
|
||||
startTransition(async () => {
|
||||
const fd = new FormData();
|
||||
fd.set("id", invoice.id);
|
||||
const result = await deleteInvoiceAction(fd);
|
||||
if (result.ok) {
|
||||
toast.success("Fatura silindi.");
|
||||
router.push("/invoices");
|
||||
} else {
|
||||
toast.error(result.error ?? "Silme başarısız.");
|
||||
setDeleting(false);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button variant="outline" size="sm" onClick={() => window.print()}>
|
||||
<Printer className="size-3.5" />
|
||||
Yazdır
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={() => setEditOpen(true)}>
|
||||
<Pencil className="size-3.5" />
|
||||
Düzenle
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="text-destructive hover:text-destructive"
|
||||
onClick={() => setDeleting(true)}
|
||||
>
|
||||
<Trash2 className="size-3.5" />
|
||||
Sil
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<InvoiceFormSheet
|
||||
open={editOpen}
|
||||
onOpenChange={setEditOpen}
|
||||
invoice={invoice}
|
||||
customers={customers}
|
||||
/>
|
||||
|
||||
<Dialog open={deleting} onOpenChange={setDeleting}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Faturayı sil</DialogTitle>
|
||||
<DialogDescription>
|
||||
<strong>{invoice.number}</strong> ve tüm kalemleri silinecek. Bu işlem geri alınamaz.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setDeleting(false)} 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,303 @@
|
||||
"use client";
|
||||
|
||||
import { useActionState, useEffect, useState, useTransition } from "react";
|
||||
import { Loader2, Plus, Save, Trash2 } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
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 { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
} from "@/components/ui/sheet";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import {
|
||||
addInvoiceItemAction,
|
||||
deleteInvoiceItemAction,
|
||||
updateInvoiceItemAction,
|
||||
} from "@/lib/appwrite/invoice-actions";
|
||||
import { initialInvoiceState } from "@/lib/appwrite/invoice-types";
|
||||
import { formatTRY } from "@/lib/format";
|
||||
|
||||
export type InvoiceItemRow = {
|
||||
id: string;
|
||||
description: string;
|
||||
quantity: number;
|
||||
unitPrice: number;
|
||||
vatRate: number;
|
||||
lineTotal: number;
|
||||
};
|
||||
|
||||
type Props = { invoiceId: string; items: InvoiceItemRow[] };
|
||||
|
||||
export function InvoiceItemsEditor({ invoiceId, items }: Props) {
|
||||
const [formOpen, setFormOpen] = useState(false);
|
||||
const [editing, setEditing] = useState<InvoiceItemRow | null>(null);
|
||||
const [deleting, setDeleting] = useState<InvoiceItemRow | null>(null);
|
||||
const [busy, startTransition] = useTransition();
|
||||
|
||||
const handleDelete = () => {
|
||||
if (!deleting) return;
|
||||
startTransition(async () => {
|
||||
const fd = new FormData();
|
||||
fd.set("id", deleting.id);
|
||||
const result = await deleteInvoiceItemAction(fd);
|
||||
if (result.ok) {
|
||||
toast.success("Kalem silindi.");
|
||||
setDeleting(null);
|
||||
} else {
|
||||
toast.error(result.error ?? "Silme başarısız.");
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Card>
|
||||
<CardContent className="p-0">
|
||||
<div className="flex items-center justify-between border-b p-4">
|
||||
<h2 className="text-sm font-semibold">Kalemler ({items.length})</h2>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
setEditing(null);
|
||||
setFormOpen(true);
|
||||
}}
|
||||
>
|
||||
<Plus className="size-3.5" />
|
||||
Kalem ekle
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Açıklama</TableHead>
|
||||
<TableHead className="w-[100px] text-right">Miktar</TableHead>
|
||||
<TableHead className="w-[140px] text-right">Birim fiyat</TableHead>
|
||||
<TableHead className="w-[80px] text-right">KDV %</TableHead>
|
||||
<TableHead className="w-[140px] text-right">Toplam</TableHead>
|
||||
<TableHead className="w-[60px]"></TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{items.length ? (
|
||||
items.map((it) => (
|
||||
<TableRow
|
||||
key={it.id}
|
||||
className="cursor-pointer"
|
||||
onClick={() => {
|
||||
setEditing(it);
|
||||
setFormOpen(true);
|
||||
}}
|
||||
>
|
||||
<TableCell className="font-medium">{it.description}</TableCell>
|
||||
<TableCell className="text-right tabular-nums">{it.quantity}</TableCell>
|
||||
<TableCell className="text-right tabular-nums">
|
||||
{formatTRY(it.unitPrice)}
|
||||
</TableCell>
|
||||
<TableCell className="text-right tabular-nums">{it.vatRate}%</TableCell>
|
||||
<TableCell className="text-right font-medium tabular-nums">
|
||||
{formatTRY(it.lineTotal)}
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-7"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setDeleting(it);
|
||||
}}
|
||||
>
|
||||
<Trash2 className="size-3.5" />
|
||||
</Button>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))
|
||||
) : (
|
||||
<TableRow>
|
||||
<TableCell colSpan={6} className="h-20 text-center">
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Henüz kalem eklenmemiş. Yukarıdan ekleyin.
|
||||
</p>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<ItemFormSheet
|
||||
open={formOpen}
|
||||
onOpenChange={(v) => {
|
||||
setFormOpen(v);
|
||||
if (!v) setEditing(null);
|
||||
}}
|
||||
invoiceId={invoiceId}
|
||||
item={editing}
|
||||
/>
|
||||
|
||||
<Dialog open={Boolean(deleting)} onOpenChange={(v) => !v && setDeleting(null)}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Kalemi sil</DialogTitle>
|
||||
<DialogDescription>
|
||||
<strong>{deleting?.description}</strong> kalemini silmek istediğinize emin misiniz?
|
||||
</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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function ItemFormSheet({
|
||||
open,
|
||||
onOpenChange,
|
||||
invoiceId,
|
||||
item,
|
||||
}: {
|
||||
open: boolean;
|
||||
onOpenChange: (v: boolean) => void;
|
||||
invoiceId: string;
|
||||
item?: InvoiceItemRow | null;
|
||||
}) {
|
||||
const isEdit = Boolean(item);
|
||||
const action = isEdit ? updateInvoiceItemAction : addInvoiceItemAction;
|
||||
const [state, formAction, isPending] = useActionState(action, initialInvoiceState);
|
||||
|
||||
useEffect(() => {
|
||||
if (state.ok) {
|
||||
toast.success(isEdit ? "Kalem güncellendi." : "Kalem 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-md">
|
||||
<SheetHeader className="border-b px-6 py-4">
|
||||
<SheetTitle>{isEdit ? "Kalemi düzenle" : "Yeni kalem"}</SheetTitle>
|
||||
</SheetHeader>
|
||||
|
||||
<form action={formAction} className="flex flex-1 flex-col">
|
||||
{isEdit && item && <input type="hidden" name="id" value={item.id} />}
|
||||
{!isEdit && <input type="hidden" name="invoiceId" value={invoiceId} />}
|
||||
|
||||
<div className="flex-1 space-y-4 overflow-y-auto px-6 py-5">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="description">Açıklama *</Label>
|
||||
<Input
|
||||
id="description"
|
||||
name="description"
|
||||
defaultValue={item?.description ?? ""}
|
||||
placeholder="Hizmet / ürün açıklaması"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 md:grid-cols-3">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="quantity">Miktar *</Label>
|
||||
<Input
|
||||
id="quantity"
|
||||
name="quantity"
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0.01"
|
||||
defaultValue={item?.quantity ?? "1"}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="unitPrice">Birim (₺) *</Label>
|
||||
<Input
|
||||
id="unitPrice"
|
||||
name="unitPrice"
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0"
|
||||
defaultValue={item?.unitPrice ?? ""}
|
||||
placeholder="0.00"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="vatRate">KDV %</Label>
|
||||
<Input
|
||||
id="vatRate"
|
||||
name="vatRate"
|
||||
type="number"
|
||||
step="0.1"
|
||||
min="0"
|
||||
max="100"
|
||||
defaultValue={item?.vatRate ?? "20"}
|
||||
/>
|
||||
</div>
|
||||
</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" : "Ekle"}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</SheetFooter>
|
||||
</form>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { notFound, redirect } from "next/navigation";
|
||||
import { ArrowLeft } from "lucide-react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { listCustomers } from "@/lib/appwrite/customer-queries";
|
||||
import { getInvoice, listInvoiceItems } from "@/lib/appwrite/invoice-queries";
|
||||
import { requireTenant } from "@/lib/appwrite/tenant-guard";
|
||||
import { formatDate, formatTRY } from "@/lib/format";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
import { STATUS_COLOR, STATUS_LABEL } from "../components/types";
|
||||
import { InvoiceItemsEditor } from "./components/items-editor";
|
||||
import { InvoiceHeaderActions } from "./components/header-actions";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "İşletmem — Fatura",
|
||||
};
|
||||
|
||||
export default async function InvoiceDetailPage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ id: string }>;
|
||||
}) {
|
||||
const { id } = await params;
|
||||
|
||||
let ctx;
|
||||
try {
|
||||
ctx = await requireTenant();
|
||||
} catch {
|
||||
redirect("/onboarding");
|
||||
}
|
||||
|
||||
const invoice = await getInvoice(ctx.tenantId, id);
|
||||
if (!invoice) notFound();
|
||||
|
||||
const [items, customers] = await Promise.all([
|
||||
listInvoiceItems(ctx.tenantId, id),
|
||||
listCustomers(ctx.tenantId),
|
||||
]);
|
||||
|
||||
const customerName = customers.find((c) => c.$id === invoice.customerId)?.name ?? "—";
|
||||
|
||||
return (
|
||||
<div className="flex-1 space-y-6 px-6 pt-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<Button asChild variant="ghost" size="sm">
|
||||
<Link href="/invoices">
|
||||
<ArrowLeft className="size-3.5" />
|
||||
Faturalar
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col items-start justify-between gap-4 md:flex-row md:items-center">
|
||||
<div>
|
||||
<p className="text-muted-foreground text-sm">{customerName}</p>
|
||||
<h1 className="font-mono text-2xl font-bold tracking-tight">{invoice.number}</h1>
|
||||
<div className="mt-2 flex flex-wrap items-center gap-3 text-sm">
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-xs",
|
||||
STATUS_COLOR[invoice.status ?? "draft"],
|
||||
)}
|
||||
>
|
||||
{STATUS_LABEL[invoice.status ?? "draft"]}
|
||||
</span>
|
||||
<span className="text-muted-foreground">
|
||||
Düzenleme: {formatDate(invoice.issueDate)}
|
||||
</span>
|
||||
<span className="text-muted-foreground">Vade: {formatDate(invoice.dueDate)}</span>
|
||||
</div>
|
||||
</div>
|
||||
<InvoiceHeaderActions
|
||||
invoice={{
|
||||
id: invoice.$id,
|
||||
number: invoice.number,
|
||||
customerId: invoice.customerId,
|
||||
customerName,
|
||||
issueDate: invoice.issueDate,
|
||||
dueDate: invoice.dueDate,
|
||||
status: invoice.status ?? "draft",
|
||||
subtotal: invoice.subtotal ?? 0,
|
||||
vatTotal: invoice.vatTotal ?? 0,
|
||||
total: invoice.total ?? 0,
|
||||
notes: invoice.notes ?? "",
|
||||
}}
|
||||
customers={customers.map((c) => ({ id: c.$id, name: c.name }))}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<InvoiceItemsEditor
|
||||
invoiceId={id}
|
||||
items={items.map((it) => ({
|
||||
id: it.$id,
|
||||
description: it.description,
|
||||
quantity: it.quantity,
|
||||
unitPrice: it.unitPrice,
|
||||
vatRate: it.vatRate ?? 0,
|
||||
lineTotal: it.lineTotal,
|
||||
}))}
|
||||
/>
|
||||
|
||||
<Card>
|
||||
<CardContent className="space-y-2 p-4">
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">Ara toplam</span>
|
||||
<span className="tabular-nums">{formatTRY(invoice.subtotal ?? 0)}</span>
|
||||
</div>
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">KDV</span>
|
||||
<span className="tabular-nums">{formatTRY(invoice.vatTotal ?? 0)}</span>
|
||||
</div>
|
||||
<div className="border-t pt-2"></div>
|
||||
<div className="flex justify-between text-base font-semibold">
|
||||
<span>Genel toplam</span>
|
||||
<span className="tabular-nums">{formatTRY(invoice.total ?? 0)}</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{invoice.notes && (
|
||||
<Card>
|
||||
<CardContent className="p-4">
|
||||
<p className="text-muted-foreground text-xs font-medium uppercase">Notlar</p>
|
||||
<p className="mt-1 whitespace-pre-line text-sm">{invoice.notes}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
"use client";
|
||||
|
||||
import { useActionState, useEffect } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
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 {
|
||||
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 {
|
||||
createInvoiceAction,
|
||||
updateInvoiceAction,
|
||||
} from "@/lib/appwrite/invoice-actions";
|
||||
import { initialInvoiceState } from "@/lib/appwrite/invoice-types";
|
||||
|
||||
import type { Customer, InvoiceRow } from "./types";
|
||||
|
||||
type Props = {
|
||||
open: boolean;
|
||||
onOpenChange: (v: boolean) => void;
|
||||
invoice?: InvoiceRow | null;
|
||||
customers: Customer[];
|
||||
};
|
||||
|
||||
function isoToDate(iso: string): string {
|
||||
if (!iso) return "";
|
||||
return iso.slice(0, 10);
|
||||
}
|
||||
|
||||
export function InvoiceFormSheet({ open, onOpenChange, invoice, customers }: Props) {
|
||||
const isEdit = Boolean(invoice);
|
||||
const action = isEdit ? updateInvoiceAction : createInvoiceAction;
|
||||
const [state, formAction, isPending] = useActionState(action, initialInvoiceState);
|
||||
const router = useRouter();
|
||||
|
||||
useEffect(() => {
|
||||
if (state.ok) {
|
||||
toast.success(isEdit ? "Fatura güncellendi." : "Fatura oluşturuldu.");
|
||||
onOpenChange(false);
|
||||
if (!isEdit && state.invoiceId) {
|
||||
router.push(`/invoices/${state.invoiceId}`);
|
||||
}
|
||||
} 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);
|
||||
const inThirty = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000)
|
||||
.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 ? "Faturayı düzenle" : "Yeni fatura"}</SheetTitle>
|
||||
<SheetDescription>
|
||||
{isEdit
|
||||
? "Fatura bilgilerini güncelleyin. Kalem eklemek için fatura detayına gidin."
|
||||
: "Faturayı oluşturun, ardından detay sayfasında kalemleri ekleyin. Numara otomatik üretilir."}
|
||||
</SheetDescription>
|
||||
</SheetHeader>
|
||||
|
||||
<form action={formAction} className="flex flex-1 flex-col">
|
||||
{isEdit && invoice && <input type="hidden" name="id" value={invoice.id} />}
|
||||
|
||||
<div className="flex-1 space-y-4 overflow-y-auto px-6 py-5">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="customerId">Müşteri *</Label>
|
||||
<Select
|
||||
name="customerId"
|
||||
defaultValue={invoice?.customerId ?? ""}
|
||||
disabled={customers.length === 0}
|
||||
>
|
||||
<SelectTrigger id="customerId">
|
||||
<SelectValue placeholder="Müşteri seçin" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{customers.map((c) => (
|
||||
<SelectItem key={c.id} value={c.id}>
|
||||
{c.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{state.fieldErrors?.customerId && (
|
||||
<p className="text-destructive text-xs">{state.fieldErrors.customerId}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="issueDate">Düzenleme tarihi *</Label>
|
||||
<Input
|
||||
id="issueDate"
|
||||
name="issueDate"
|
||||
type="date"
|
||||
defaultValue={isoToDate(invoice?.issueDate ?? today)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="dueDate">Vade tarihi *</Label>
|
||||
<Input
|
||||
id="dueDate"
|
||||
name="dueDate"
|
||||
type="date"
|
||||
defaultValue={isoToDate(invoice?.dueDate ?? inThirty)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="status">Durum</Label>
|
||||
<Select name="status" defaultValue={invoice?.status ?? "draft"}>
|
||||
<SelectTrigger id="status">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="draft">Taslak</SelectItem>
|
||||
<SelectItem value="sent">Gönderildi</SelectItem>
|
||||
<SelectItem value="paid">Ödendi</SelectItem>
|
||||
<SelectItem value="overdue">Gecikmiş</SelectItem>
|
||||
<SelectItem value="cancelled">İptal</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="notes">Notlar</Label>
|
||||
<Textarea
|
||||
id="notes"
|
||||
name="notes"
|
||||
rows={4}
|
||||
defaultValue={invoice?.notes ?? ""}
|
||||
placeholder="Faturada görünecek not, ödeme talimatları, 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 || customers.length === 0}>
|
||||
{isPending ? (
|
||||
<>
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
Kaydediliyor...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Save className="size-4" />
|
||||
{isEdit ? "Güncelle" : "Oluştur"}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</SheetFooter>
|
||||
</form>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
"use client";
|
||||
|
||||
import { useMemo, useState, useTransition } from "react";
|
||||
import Link from "next/link";
|
||||
import {
|
||||
type ColumnDef,
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
getFilteredRowModel,
|
||||
getPaginationRowModel,
|
||||
getSortedRowModel,
|
||||
type SortingState,
|
||||
useReactTable,
|
||||
} from "@tanstack/react-table";
|
||||
import {
|
||||
ArrowUpRight,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
ExternalLink,
|
||||
Loader2,
|
||||
MoreHorizontal,
|
||||
Plus,
|
||||
Receipt,
|
||||
Search,
|
||||
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,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import { deleteInvoiceAction } from "@/lib/appwrite/invoice-actions";
|
||||
import { formatDate, formatTRY } from "@/lib/format";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
import { InvoiceFormSheet } from "./invoice-form-sheet";
|
||||
import { type Customer, type InvoiceRow, STATUS_COLOR, STATUS_LABEL } from "./types";
|
||||
|
||||
type Props = { invoices: InvoiceRow[]; customers: Customer[] };
|
||||
|
||||
export function InvoicesClient({ invoices, customers }: Props) {
|
||||
const [search, setSearch] = useState("");
|
||||
const [sorting, setSorting] = useState<SortingState>([]);
|
||||
const [formOpen, setFormOpen] = useState(false);
|
||||
const [deleting, setDeleting] = useState<InvoiceRow | null>(null);
|
||||
const [busy, startTransition] = useTransition();
|
||||
|
||||
const stats = useMemo(() => {
|
||||
let total = 0;
|
||||
let outstanding = 0;
|
||||
let paid = 0;
|
||||
let overdue = 0;
|
||||
for (const i of invoices) {
|
||||
total += i.total;
|
||||
if (i.status === "paid") paid += i.total;
|
||||
else if (i.status === "overdue") {
|
||||
outstanding += i.total;
|
||||
overdue += i.total;
|
||||
} else if (i.status === "sent" || i.status === "draft") outstanding += i.total;
|
||||
}
|
||||
return { total, outstanding, paid, overdue };
|
||||
}, [invoices]);
|
||||
|
||||
const columns = useMemo<ColumnDef<InvoiceRow>[]>(
|
||||
() => [
|
||||
{
|
||||
accessorKey: "number",
|
||||
header: "Numara",
|
||||
cell: ({ row }) => (
|
||||
<Link
|
||||
href={`/invoices/${row.original.id}`}
|
||||
className="hover:text-primary inline-flex items-center gap-1 font-mono text-sm font-medium"
|
||||
>
|
||||
{row.original.number}
|
||||
<ExternalLink className="size-3 opacity-0 transition-opacity group-hover:opacity-100" />
|
||||
</Link>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "customerName",
|
||||
header: "Müşteri",
|
||||
cell: ({ row }) => row.original.customerName,
|
||||
},
|
||||
{
|
||||
accessorKey: "issueDate",
|
||||
header: "Tarih",
|
||||
cell: ({ row }) => (
|
||||
<span className="text-muted-foreground">{formatDate(row.original.issueDate)}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "dueDate",
|
||||
header: "Vade",
|
||||
cell: ({ row }) => {
|
||||
const overdue =
|
||||
row.original.status !== "paid" &&
|
||||
row.original.status !== "cancelled" &&
|
||||
new Date(row.original.dueDate) < new Date();
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"text-muted-foreground",
|
||||
overdue && "text-destructive font-medium",
|
||||
)}
|
||||
>
|
||||
{formatDate(row.original.dueDate)}
|
||||
</span>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
header: "Durum",
|
||||
cell: ({ row }) => (
|
||||
<Badge variant="outline" className={cn("border-0", STATUS_COLOR[row.original.status])}>
|
||||
{STATUS_LABEL[row.original.status]}
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "total",
|
||||
header: "Toplam",
|
||||
cell: ({ row }) => (
|
||||
<span className="font-medium tabular-nums">{formatTRY(row.original.total)}</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 asChild>
|
||||
<Link href={`/invoices/${row.original.id}`}>
|
||||
<ArrowUpRight className="size-3.5" />
|
||||
Aç
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
variant="destructive"
|
||||
onClick={() => setDeleting(row.original)}
|
||||
>
|
||||
<Trash2 className="size-3.5" />
|
||||
Sil
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
],
|
||||
[],
|
||||
);
|
||||
|
||||
const table = useReactTable({
|
||||
data: invoices,
|
||||
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.number, row.original.customerName, row.original.notes]
|
||||
.join(" ")
|
||||
.toLowerCase()
|
||||
.includes(v);
|
||||
},
|
||||
});
|
||||
|
||||
const handleDelete = () => {
|
||||
if (!deleting) return;
|
||||
startTransition(async () => {
|
||||
const fd = new FormData();
|
||||
fd.set("id", deleting.id);
|
||||
const result = await deleteInvoiceAction(fd);
|
||||
if (result.ok) {
|
||||
toast.success("Fatura silindi.");
|
||||
setDeleting(null);
|
||||
} else {
|
||||
toast.error(result.error ?? "Silme başarısız.");
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="grid grid-cols-2 gap-3 md:grid-cols-4">
|
||||
<Card>
|
||||
<CardContent className="p-4">
|
||||
<p className="text-muted-foreground text-xs">Toplam</p>
|
||||
<p className="mt-1 text-xl font-semibold">{formatTRY(stats.total)}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardContent className="p-4">
|
||||
<p className="text-muted-foreground text-xs">Tahsil edildi</p>
|
||||
<p className="mt-1 text-xl font-semibold text-emerald-600 dark:text-emerald-400">
|
||||
{formatTRY(stats.paid)}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardContent className="p-4">
|
||||
<p className="text-muted-foreground text-xs">Bekleyen</p>
|
||||
<p className="mt-1 text-xl font-semibold text-blue-600 dark:text-blue-400">
|
||||
{formatTRY(stats.outstanding)}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardContent className="p-4">
|
||||
<p className="text-muted-foreground text-xs">Gecikmiş</p>
|
||||
<p className="mt-1 text-xl font-semibold text-red-600 dark:text-red-400">
|
||||
{formatTRY(stats.overdue)}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</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="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="Numara, müşteri, not..."
|
||||
className="pl-9"
|
||||
/>
|
||||
</div>
|
||||
<Button onClick={() => setFormOpen(true)} disabled={customers.length === 0}>
|
||||
<Plus className="size-4" />
|
||||
Yeni fatura
|
||||
</Button>
|
||||
</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} className="group">
|
||||
{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">
|
||||
<div className="text-muted-foreground flex flex-col items-center gap-2">
|
||||
<Receipt className="size-6" />
|
||||
<p className="text-sm">
|
||||
{customers.length === 0
|
||||
? "Önce müşteri ekleyin, sonra fatura kesebilirsiniz."
|
||||
: "Henüz fatura yok."}
|
||||
</p>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
|
||||
<div className="flex items-center justify-between border-t px-4 py-3">
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Toplam {table.getFilteredRowModel().rows.length} fatura
|
||||
</p>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
className="size-8"
|
||||
onClick={() => table.previousPage()}
|
||||
disabled={!table.getCanPreviousPage()}
|
||||
>
|
||||
<ChevronLeft className="size-4" />
|
||||
</Button>
|
||||
<span className="text-muted-foreground text-sm">
|
||||
Sayfa {table.getState().pagination.pageIndex + 1} /{" "}
|
||||
{Math.max(table.getPageCount(), 1)}
|
||||
</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
className="size-8"
|
||||
onClick={() => table.nextPage()}
|
||||
disabled={!table.getCanNextPage()}
|
||||
>
|
||||
<ChevronRight className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<InvoiceFormSheet
|
||||
open={formOpen}
|
||||
onOpenChange={setFormOpen}
|
||||
customers={customers}
|
||||
/>
|
||||
|
||||
<Dialog open={Boolean(deleting)} onOpenChange={(v) => !v && setDeleting(null)}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Faturayı sil</DialogTitle>
|
||||
<DialogDescription>
|
||||
<strong>{deleting?.number}</strong> ve tüm kalemleri silinecek. Bu işlem geri alınamaz.
|
||||
</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,33 @@
|
||||
export type InvoiceStatus = "draft" | "sent" | "paid" | "overdue" | "cancelled";
|
||||
|
||||
export type InvoiceRow = {
|
||||
id: string;
|
||||
number: string;
|
||||
customerId: string;
|
||||
customerName: string;
|
||||
issueDate: string;
|
||||
dueDate: string;
|
||||
status: InvoiceStatus;
|
||||
subtotal: number;
|
||||
vatTotal: number;
|
||||
total: number;
|
||||
notes: string;
|
||||
};
|
||||
|
||||
export type Customer = { id: string; name: string };
|
||||
|
||||
export const STATUS_LABEL: Record<InvoiceStatus, string> = {
|
||||
draft: "Taslak",
|
||||
sent: "Gönderildi",
|
||||
paid: "Ödendi",
|
||||
overdue: "Gecikmiş",
|
||||
cancelled: "İptal",
|
||||
};
|
||||
|
||||
export const STATUS_COLOR: Record<InvoiceStatus, string> = {
|
||||
draft: "bg-slate-500/15 text-slate-700 dark:text-slate-300 border-slate-500/30",
|
||||
sent: "bg-blue-500/15 text-blue-700 dark:text-blue-300 border-blue-500/30",
|
||||
paid: "bg-emerald-500/15 text-emerald-700 dark:text-emerald-300 border-emerald-500/30",
|
||||
overdue: "bg-red-500/15 text-red-700 dark:text-red-300 border-red-500/30",
|
||||
cancelled: "bg-muted text-muted-foreground border-muted-foreground/30",
|
||||
};
|
||||
@@ -0,0 +1,56 @@
|
||||
import type { Metadata } from "next";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
import { listCustomers } from "@/lib/appwrite/customer-queries";
|
||||
import { listInvoices } from "@/lib/appwrite/invoice-queries";
|
||||
import { requireTenant } from "@/lib/appwrite/tenant-guard";
|
||||
import { InvoicesClient } from "./components/invoices-client";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "İşletmem — Faturalar",
|
||||
};
|
||||
|
||||
export default async function InvoicesPage() {
|
||||
let ctx;
|
||||
try {
|
||||
ctx = await requireTenant();
|
||||
} catch {
|
||||
redirect("/onboarding");
|
||||
}
|
||||
|
||||
const [invoices, customers] = await Promise.all([
|
||||
listInvoices(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">Faturalar</h1>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Müşterilerinize fatura kesin, kalemleri yönetin, durumu takip edin.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<InvoicesClient
|
||||
invoices={invoices.map((i) => ({
|
||||
id: i.$id,
|
||||
number: i.number,
|
||||
customerId: i.customerId,
|
||||
customerName: customerMap.get(i.customerId) ?? "—",
|
||||
issueDate: i.issueDate,
|
||||
dueDate: i.dueDate,
|
||||
status: i.status ?? "draft",
|
||||
subtotal: i.subtotal ?? 0,
|
||||
vatTotal: i.vatTotal ?? 0,
|
||||
total: i.total ?? 0,
|
||||
notes: i.notes ?? "",
|
||||
}))}
|
||||
customers={customers.map((c) => ({ id: c.$id, name: c.name }))}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,486 @@
|
||||
"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 Invoice,
|
||||
type InvoiceItem,
|
||||
type TenantSettings,
|
||||
} from "./schema";
|
||||
import { createAdminClient } from "./server";
|
||||
import { requireTenant } from "./tenant-guard";
|
||||
import type { InvoiceActionState } from "./invoice-types";
|
||||
import { invoiceItemSchema, invoiceSchema } from "@/lib/validation/invoices";
|
||||
|
||||
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 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;
|
||||
}
|
||||
|
||||
async function nextInvoiceNumber(
|
||||
tenantId: string,
|
||||
): Promise<{ number: string; settingsId: string | null }> {
|
||||
const { tablesDB } = createAdminClient();
|
||||
const result = await tablesDB.listRows({
|
||||
databaseId: DATABASE_ID,
|
||||
tableId: TABLES.tenantSettings,
|
||||
queries: [Query.equal("tenantId", tenantId), Query.limit(1)],
|
||||
});
|
||||
const settings = result.rows[0] as unknown as TenantSettings | undefined;
|
||||
const prefix = settings?.invoicePrefix || "INV";
|
||||
const counter = (settings?.invoiceCounter ?? 0) + 1;
|
||||
const year = new Date().getFullYear();
|
||||
const number = `${prefix}-${year}-${String(counter).padStart(4, "0")}`;
|
||||
|
||||
if (settings) {
|
||||
await tablesDB.updateRow(DATABASE_ID, TABLES.tenantSettings, settings.$id, {
|
||||
invoiceCounter: counter,
|
||||
});
|
||||
return { number, settingsId: settings.$id };
|
||||
}
|
||||
return { number, settingsId: null };
|
||||
}
|
||||
|
||||
async function recomputeTotals(
|
||||
tenantId: string,
|
||||
invoiceId: string,
|
||||
): Promise<{ subtotal: number; vatTotal: number; total: number }> {
|
||||
const { tablesDB } = createAdminClient();
|
||||
const result = await tablesDB.listRows({
|
||||
databaseId: DATABASE_ID,
|
||||
tableId: TABLES.invoiceItems,
|
||||
queries: [
|
||||
Query.equal("tenantId", tenantId),
|
||||
Query.equal("invoiceId", invoiceId),
|
||||
Query.limit(500),
|
||||
],
|
||||
});
|
||||
let subtotal = 0;
|
||||
let vatTotal = 0;
|
||||
for (const r of result.rows as unknown as InvoiceItem[]) {
|
||||
const lineNet = (r.quantity ?? 0) * (r.unitPrice ?? 0);
|
||||
const lineVat = lineNet * ((r.vatRate ?? 0) / 100);
|
||||
subtotal += lineNet;
|
||||
vatTotal += lineVat;
|
||||
}
|
||||
const total = subtotal + vatTotal;
|
||||
await tablesDB.updateRow(DATABASE_ID, TABLES.invoices, invoiceId, {
|
||||
subtotal: Number(subtotal.toFixed(2)),
|
||||
vatTotal: Number(vatTotal.toFixed(2)),
|
||||
total: Number(total.toFixed(2)),
|
||||
});
|
||||
return { subtotal, vatTotal, total };
|
||||
}
|
||||
|
||||
// -------------------- Invoice header --------------------
|
||||
|
||||
function pickInvoiceFields(formData: FormData) {
|
||||
return {
|
||||
customerId: String(formData.get("customerId") ?? ""),
|
||||
issueDate: String(formData.get("issueDate") ?? ""),
|
||||
dueDate: String(formData.get("dueDate") ?? ""),
|
||||
status:
|
||||
(formData.get("status") as "draft" | "sent" | "paid" | "overdue" | "cancelled" | null) ??
|
||||
"draft",
|
||||
notes: String(formData.get("notes") ?? "").trim(),
|
||||
};
|
||||
}
|
||||
|
||||
export async function createInvoiceAction(
|
||||
_prev: InvoiceActionState,
|
||||
formData: FormData,
|
||||
): Promise<InvoiceActionState> {
|
||||
let ctx;
|
||||
try {
|
||||
ctx = await requireTenant();
|
||||
} catch {
|
||||
return { ok: false, error: "Yetkiniz yok." };
|
||||
}
|
||||
|
||||
const parsed = invoiceSchema.safeParse(pickInvoiceFields(formData));
|
||||
if (!parsed.success) {
|
||||
return { ok: false, error: "Form geçersiz.", fieldErrors: flattenErrors(parsed.error) };
|
||||
}
|
||||
|
||||
let invoiceId = "";
|
||||
try {
|
||||
const { tablesDB } = createAdminClient();
|
||||
const { number } = await nextInvoiceNumber(ctx.tenantId);
|
||||
|
||||
const data = {
|
||||
...parsed.data,
|
||||
issueDate: toIso(parsed.data.issueDate),
|
||||
dueDate: toIso(parsed.data.dueDate),
|
||||
number,
|
||||
subtotal: 0,
|
||||
vatTotal: 0,
|
||||
total: 0,
|
||||
};
|
||||
|
||||
const row = await tablesDB.createRow(
|
||||
DATABASE_ID,
|
||||
TABLES.invoices,
|
||||
ID.unique(),
|
||||
{
|
||||
tenantId: ctx.tenantId,
|
||||
createdBy: ctx.user.id,
|
||||
...data,
|
||||
},
|
||||
teamRowPermissions(ctx.tenantId),
|
||||
);
|
||||
invoiceId = row.$id;
|
||||
|
||||
await logAudit({
|
||||
tenantId: ctx.tenantId,
|
||||
userId: ctx.user.id,
|
||||
action: "create",
|
||||
entityType: "invoice",
|
||||
entityId: row.$id,
|
||||
changes: { number, customerId: parsed.data.customerId },
|
||||
});
|
||||
} catch (e) {
|
||||
return { ok: false, error: appwriteError(e) };
|
||||
}
|
||||
|
||||
revalidatePath("/invoices");
|
||||
return { ok: true, invoiceId };
|
||||
}
|
||||
|
||||
export async function updateInvoiceAction(
|
||||
_prev: InvoiceActionState,
|
||||
formData: FormData,
|
||||
): Promise<InvoiceActionState> {
|
||||
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 = invoiceSchema.safeParse(pickInvoiceFields(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.invoices,
|
||||
id,
|
||||
)) as unknown as Invoice;
|
||||
if (existing.tenantId !== ctx.tenantId) {
|
||||
return { ok: false, error: "Erişim engellendi." };
|
||||
}
|
||||
|
||||
const data = {
|
||||
...parsed.data,
|
||||
issueDate: toIso(parsed.data.issueDate),
|
||||
dueDate: toIso(parsed.data.dueDate),
|
||||
};
|
||||
await tablesDB.updateRow(DATABASE_ID, TABLES.invoices, id, data);
|
||||
|
||||
await logAudit({
|
||||
tenantId: ctx.tenantId,
|
||||
userId: ctx.user.id,
|
||||
action: "update",
|
||||
entityType: "invoice",
|
||||
entityId: id,
|
||||
changes: data,
|
||||
});
|
||||
} catch (e) {
|
||||
return { ok: false, error: appwriteError(e) };
|
||||
}
|
||||
|
||||
revalidatePath("/invoices");
|
||||
revalidatePath(`/invoices/${id}`);
|
||||
return { ok: true, invoiceId: id };
|
||||
}
|
||||
|
||||
export async function deleteInvoiceAction(
|
||||
formData: FormData,
|
||||
): Promise<InvoiceActionState> {
|
||||
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.invoices,
|
||||
id,
|
||||
)) as unknown as Invoice;
|
||||
if (existing.tenantId !== ctx.tenantId) {
|
||||
return { ok: false, error: "Erişim engellendi." };
|
||||
}
|
||||
|
||||
// Delete items first
|
||||
const items = await tablesDB.listRows({
|
||||
databaseId: DATABASE_ID,
|
||||
tableId: TABLES.invoiceItems,
|
||||
queries: [
|
||||
Query.equal("tenantId", ctx.tenantId),
|
||||
Query.equal("invoiceId", id),
|
||||
Query.limit(500),
|
||||
],
|
||||
});
|
||||
for (const it of items.rows) {
|
||||
await tablesDB.deleteRow(DATABASE_ID, TABLES.invoiceItems, it.$id);
|
||||
}
|
||||
|
||||
await tablesDB.deleteRow(DATABASE_ID, TABLES.invoices, id);
|
||||
|
||||
await logAudit({
|
||||
tenantId: ctx.tenantId,
|
||||
userId: ctx.user.id,
|
||||
action: "delete",
|
||||
entityType: "invoice",
|
||||
entityId: id,
|
||||
changes: { number: existing.number, items: items.rows.length },
|
||||
});
|
||||
} catch (e) {
|
||||
return { ok: false, error: appwriteError(e) };
|
||||
}
|
||||
|
||||
revalidatePath("/invoices");
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
// -------------------- Invoice items --------------------
|
||||
|
||||
function pickItemFields(formData: FormData) {
|
||||
return {
|
||||
description: String(formData.get("description") ?? "").trim(),
|
||||
quantity: String(formData.get("quantity") ?? "1"),
|
||||
unitPrice: String(formData.get("unitPrice") ?? "0"),
|
||||
vatRate: String(formData.get("vatRate") ?? "20"),
|
||||
};
|
||||
}
|
||||
|
||||
function lineTotal(qty: number, unitPrice: number, vatRate: number): number {
|
||||
const net = qty * unitPrice;
|
||||
const vat = net * (vatRate / 100);
|
||||
return Number((net + vat).toFixed(2));
|
||||
}
|
||||
|
||||
export async function addInvoiceItemAction(
|
||||
_prev: InvoiceActionState,
|
||||
formData: FormData,
|
||||
): Promise<InvoiceActionState> {
|
||||
const invoiceId = String(formData.get("invoiceId") ?? "");
|
||||
if (!invoiceId) return { ok: false, error: "Fatura ID eksik." };
|
||||
|
||||
let ctx;
|
||||
try {
|
||||
ctx = await requireTenant();
|
||||
} catch {
|
||||
return { ok: false, error: "Yetkiniz yok." };
|
||||
}
|
||||
|
||||
const parsed = invoiceItemSchema.safeParse(pickItemFields(formData));
|
||||
if (!parsed.success) {
|
||||
return { ok: false, error: "Kalem geçersiz.", fieldErrors: flattenErrors(parsed.error) };
|
||||
}
|
||||
|
||||
try {
|
||||
const { tablesDB } = createAdminClient();
|
||||
const invoice = (await tablesDB.getRow(
|
||||
DATABASE_ID,
|
||||
TABLES.invoices,
|
||||
invoiceId,
|
||||
)) as unknown as Invoice;
|
||||
if (invoice.tenantId !== ctx.tenantId) {
|
||||
return { ok: false, error: "Erişim engellendi." };
|
||||
}
|
||||
|
||||
const total = lineTotal(parsed.data.quantity, parsed.data.unitPrice, parsed.data.vatRate ?? 0);
|
||||
|
||||
const row = await tablesDB.createRow(
|
||||
DATABASE_ID,
|
||||
TABLES.invoiceItems,
|
||||
ID.unique(),
|
||||
{
|
||||
tenantId: ctx.tenantId,
|
||||
createdBy: ctx.user.id,
|
||||
invoiceId,
|
||||
description: parsed.data.description,
|
||||
quantity: parsed.data.quantity,
|
||||
unitPrice: parsed.data.unitPrice,
|
||||
vatRate: parsed.data.vatRate ?? 0,
|
||||
lineTotal: total,
|
||||
},
|
||||
teamRowPermissions(ctx.tenantId),
|
||||
);
|
||||
|
||||
await recomputeTotals(ctx.tenantId, invoiceId);
|
||||
|
||||
await logAudit({
|
||||
tenantId: ctx.tenantId,
|
||||
userId: ctx.user.id,
|
||||
action: "create",
|
||||
entityType: "invoice_item",
|
||||
entityId: row.$id,
|
||||
changes: { invoiceId, ...parsed.data, lineTotal: total },
|
||||
});
|
||||
} catch (e) {
|
||||
return { ok: false, error: appwriteError(e) };
|
||||
}
|
||||
|
||||
revalidatePath(`/invoices/${invoiceId}`);
|
||||
return { ok: true, invoiceId };
|
||||
}
|
||||
|
||||
export async function updateInvoiceItemAction(
|
||||
_prev: InvoiceActionState,
|
||||
formData: FormData,
|
||||
): Promise<InvoiceActionState> {
|
||||
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 = invoiceItemSchema.safeParse(pickItemFields(formData));
|
||||
if (!parsed.success) {
|
||||
return { ok: false, error: "Kalem geçersiz.", fieldErrors: flattenErrors(parsed.error) };
|
||||
}
|
||||
|
||||
try {
|
||||
const { tablesDB } = createAdminClient();
|
||||
const existing = (await tablesDB.getRow(
|
||||
DATABASE_ID,
|
||||
TABLES.invoiceItems,
|
||||
id,
|
||||
)) as unknown as InvoiceItem;
|
||||
if (existing.tenantId !== ctx.tenantId) {
|
||||
return { ok: false, error: "Erişim engellendi." };
|
||||
}
|
||||
|
||||
const total = lineTotal(parsed.data.quantity, parsed.data.unitPrice, parsed.data.vatRate ?? 0);
|
||||
|
||||
await tablesDB.updateRow(DATABASE_ID, TABLES.invoiceItems, id, {
|
||||
description: parsed.data.description,
|
||||
quantity: parsed.data.quantity,
|
||||
unitPrice: parsed.data.unitPrice,
|
||||
vatRate: parsed.data.vatRate ?? 0,
|
||||
lineTotal: total,
|
||||
});
|
||||
|
||||
await recomputeTotals(ctx.tenantId, existing.invoiceId);
|
||||
|
||||
await logAudit({
|
||||
tenantId: ctx.tenantId,
|
||||
userId: ctx.user.id,
|
||||
action: "update",
|
||||
entityType: "invoice_item",
|
||||
entityId: id,
|
||||
changes: { ...parsed.data, lineTotal: total },
|
||||
});
|
||||
} catch (e) {
|
||||
return { ok: false, error: appwriteError(e) };
|
||||
}
|
||||
|
||||
revalidatePath(`/invoices/${(await getItemInvoiceId(id)) ?? ""}`);
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
async function getItemInvoiceId(itemId: string): Promise<string | null> {
|
||||
try {
|
||||
const { tablesDB } = createAdminClient();
|
||||
const row = (await tablesDB.getRow(
|
||||
DATABASE_ID,
|
||||
TABLES.invoiceItems,
|
||||
itemId,
|
||||
)) as unknown as InvoiceItem;
|
||||
return row.invoiceId;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteInvoiceItemAction(
|
||||
formData: FormData,
|
||||
): Promise<InvoiceActionState> {
|
||||
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.invoiceItems,
|
||||
id,
|
||||
)) as unknown as InvoiceItem;
|
||||
if (existing.tenantId !== ctx.tenantId) {
|
||||
return { ok: false, error: "Erişim engellendi." };
|
||||
}
|
||||
|
||||
await tablesDB.deleteRow(DATABASE_ID, TABLES.invoiceItems, id);
|
||||
await recomputeTotals(ctx.tenantId, existing.invoiceId);
|
||||
|
||||
await logAudit({
|
||||
tenantId: ctx.tenantId,
|
||||
userId: ctx.user.id,
|
||||
action: "delete",
|
||||
entityType: "invoice_item",
|
||||
entityId: id,
|
||||
changes: { invoiceId: existing.invoiceId },
|
||||
});
|
||||
|
||||
revalidatePath(`/invoices/${existing.invoiceId}`);
|
||||
} catch (e) {
|
||||
return { ok: false, error: appwriteError(e) };
|
||||
}
|
||||
|
||||
return { ok: true };
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import "server-only";
|
||||
|
||||
import { Query } from "node-appwrite";
|
||||
|
||||
import { createAdminClient } from "./server";
|
||||
import { DATABASE_ID, TABLES, type Invoice, type InvoiceItem } from "./schema";
|
||||
|
||||
export async function listInvoices(tenantId: string): Promise<Invoice[]> {
|
||||
try {
|
||||
const { tablesDB } = createAdminClient();
|
||||
const result = await tablesDB.listRows({
|
||||
databaseId: DATABASE_ID,
|
||||
tableId: TABLES.invoices,
|
||||
queries: [
|
||||
Query.equal("tenantId", tenantId),
|
||||
Query.orderDesc("issueDate"),
|
||||
Query.limit(500),
|
||||
],
|
||||
});
|
||||
return result.rows as unknown as Invoice[];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export async function getInvoice(
|
||||
tenantId: string,
|
||||
id: string,
|
||||
): Promise<Invoice | null> {
|
||||
try {
|
||||
const { tablesDB } = createAdminClient();
|
||||
const row = (await tablesDB.getRow(
|
||||
DATABASE_ID,
|
||||
TABLES.invoices,
|
||||
id,
|
||||
)) as unknown as Invoice;
|
||||
if (row.tenantId !== tenantId) return null;
|
||||
return row;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function listInvoiceItems(
|
||||
tenantId: string,
|
||||
invoiceId: string,
|
||||
): Promise<InvoiceItem[]> {
|
||||
try {
|
||||
const { tablesDB } = createAdminClient();
|
||||
const result = await tablesDB.listRows({
|
||||
databaseId: DATABASE_ID,
|
||||
tableId: TABLES.invoiceItems,
|
||||
queries: [
|
||||
Query.equal("tenantId", tenantId),
|
||||
Query.equal("invoiceId", invoiceId),
|
||||
Query.orderAsc("$createdAt"),
|
||||
Query.limit(500),
|
||||
],
|
||||
});
|
||||
return result.rows as unknown as InvoiceItem[];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
export type InvoiceActionState = {
|
||||
ok: boolean;
|
||||
error?: string;
|
||||
fieldErrors?: Record<string, string>;
|
||||
invoiceId?: string;
|
||||
};
|
||||
|
||||
export const initialInvoiceState: InvoiceActionState = { ok: false };
|
||||
@@ -0,0 +1,36 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const invoiceSchema = z.object({
|
||||
customerId: z.string().min(1, "Müşteri seçin."),
|
||||
issueDate: z.string().min(1, "Düzenleme tarihi zorunlu."),
|
||||
dueDate: z.string().min(1, "Vade tarihi zorunlu."),
|
||||
status: z
|
||||
.enum(["draft", "sent", "paid", "overdue", "cancelled"])
|
||||
.optional()
|
||||
.default("draft"),
|
||||
notes: z.string().trim().max(2000).optional().transform((v) => (v ? v : undefined)),
|
||||
});
|
||||
|
||||
export type InvoiceInput = z.infer<typeof invoiceSchema>;
|
||||
|
||||
export const invoiceItemSchema = z.object({
|
||||
description: z.string().trim().min(1, "Açıklama zorunlu.").max(1000),
|
||||
quantity: z
|
||||
.union([z.number(), z.string()])
|
||||
.transform((v) => (typeof v === "string" ? Number(v.replace(",", ".")) : v))
|
||||
.pipe(z.number().positive("Miktar 0'dan büyük olmalı.")),
|
||||
unitPrice: z
|
||||
.union([z.number(), z.string()])
|
||||
.transform((v) => (typeof v === "string" ? Number(v.replace(",", ".")) : v))
|
||||
.pipe(z.number().nonnegative("Negatif olamaz.")),
|
||||
vatRate: 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;
|
||||
}),
|
||||
});
|
||||
|
||||
export type InvoiceItemInput = z.infer<typeof invoiceItemSchema>;
|
||||
Reference in New Issue
Block a user