feat(services): customer-linked services CRUD module
Same pattern as customers. Each service belongs to one customer (FK), has unit price (TRY), billing period (monthly/yearly/onetime), and recurring flag. - lib/validation/services.ts: Zod schema with TRY price coercion (accepts comma decimal), enum billing period, recurring boolean coercion. - lib/appwrite/service-actions.ts: createServiceAction, updateServiceAction, deleteServiceAction. Same tenant guard, audit log, team-scoped row perms. - lib/appwrite/service-queries.ts: listServices, listServicesByCustomer. - lib/format.ts: formatTRY (Intl.NumberFormat tr-TR), formatDate/DateTime, BILLING_PERIOD_LABEL mapping (Aylık/Yıllık/Tek seferlik). - /services page (server): joins services with customer names via in-memory map. - ServicesClient: TanStack table with global filter (name/customer/desc), Repeat icon next to recurring badges, formatted TRY column. - ServiceFormSheet: customer dropdown (disabled if no customers exist), unit price + billing period + recurring switch. - DeleteServiceDialog: same destructive confirmation pattern. Empty state on /services CTA's user back to add a customer first if none exist.
This commit is contained in:
@@ -0,0 +1,76 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useTransition } from "react";
|
||||||
|
import { Loader2, 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 { deleteServiceAction } from "@/lib/appwrite/service-actions";
|
||||||
|
|
||||||
|
export function DeleteServiceDialog({
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
id,
|
||||||
|
name,
|
||||||
|
}: {
|
||||||
|
open: boolean;
|
||||||
|
onOpenChange: (v: boolean) => void;
|
||||||
|
id: string | null;
|
||||||
|
name: string;
|
||||||
|
}) {
|
||||||
|
const [isPending, startTransition] = useTransition();
|
||||||
|
|
||||||
|
const handleDelete = () => {
|
||||||
|
if (!id) return;
|
||||||
|
startTransition(async () => {
|
||||||
|
const fd = new FormData();
|
||||||
|
fd.set("id", id);
|
||||||
|
const result = await deleteServiceAction(fd);
|
||||||
|
if (result.ok) {
|
||||||
|
toast.success("Hizmet silindi.");
|
||||||
|
onOpenChange(false);
|
||||||
|
} else {
|
||||||
|
toast.error(result.error ?? "Silme başarısız.");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Hizmeti sil</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
<strong>{name}</strong> kalıcı olarak silinecek. Bu işlem geri alınamaz.
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={isPending}>
|
||||||
|
Vazgeç
|
||||||
|
</Button>
|
||||||
|
<Button variant="destructive" onClick={handleDelete} disabled={isPending}>
|
||||||
|
{isPending ? (
|
||||||
|
<>
|
||||||
|
<Loader2 className="size-4 animate-spin" />
|
||||||
|
Siliniyor...
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Trash2 className="size-4" />
|
||||||
|
Sil
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
"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 {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from "@/components/ui/select";
|
||||||
|
import {
|
||||||
|
Sheet,
|
||||||
|
SheetContent,
|
||||||
|
SheetDescription,
|
||||||
|
SheetFooter,
|
||||||
|
SheetHeader,
|
||||||
|
SheetTitle,
|
||||||
|
} from "@/components/ui/sheet";
|
||||||
|
import { Switch } from "@/components/ui/switch";
|
||||||
|
import { Textarea } from "@/components/ui/textarea";
|
||||||
|
import {
|
||||||
|
createServiceAction,
|
||||||
|
updateServiceAction,
|
||||||
|
} from "@/lib/appwrite/service-actions";
|
||||||
|
import { initialServiceState } from "@/lib/appwrite/service-types";
|
||||||
|
import type { CustomerOption, ServiceRow } from "./types";
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
open: boolean;
|
||||||
|
onOpenChange: (v: boolean) => void;
|
||||||
|
service?: ServiceRow | null;
|
||||||
|
customers: CustomerOption[];
|
||||||
|
defaultCustomerId?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function ServiceFormSheet({
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
service,
|
||||||
|
customers,
|
||||||
|
defaultCustomerId,
|
||||||
|
}: Props) {
|
||||||
|
const isEdit = Boolean(service);
|
||||||
|
const action = isEdit ? updateServiceAction : createServiceAction;
|
||||||
|
const [state, formAction, isPending] = useActionState(action, initialServiceState);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (state.ok) {
|
||||||
|
toast.success(isEdit ? "Hizmet güncellendi." : "Hizmet 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 ? "Hizmeti düzenle" : "Yeni hizmet"}</SheetTitle>
|
||||||
|
<SheetDescription>
|
||||||
|
{customers.length === 0
|
||||||
|
? "Hizmet eklemek için önce en az bir müşteri tanımlamalısınız."
|
||||||
|
: "Müşteriye sunduğunuz hizmeti tanımlayın."}
|
||||||
|
</SheetDescription>
|
||||||
|
</SheetHeader>
|
||||||
|
|
||||||
|
<form action={formAction} className="flex flex-1 flex-col">
|
||||||
|
{isEdit && service && <input type="hidden" name="id" value={service.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={service?.customerId ?? defaultCustomerId ?? ""}
|
||||||
|
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-2">
|
||||||
|
<Label htmlFor="name">Hizmet adı *</Label>
|
||||||
|
<Input
|
||||||
|
id="name"
|
||||||
|
name="name"
|
||||||
|
defaultValue={service?.name ?? ""}
|
||||||
|
placeholder="Örn. Web hosting bakımı"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
{state.fieldErrors?.name && (
|
||||||
|
<p className="text-destructive text-xs">{state.fieldErrors.name}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid gap-2">
|
||||||
|
<Label htmlFor="description">Açıklama</Label>
|
||||||
|
<Textarea
|
||||||
|
id="description"
|
||||||
|
name="description"
|
||||||
|
rows={3}
|
||||||
|
defaultValue={service?.description ?? ""}
|
||||||
|
placeholder="Hizmetin kapsamı, sınırları, vb."
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid gap-4 md:grid-cols-2">
|
||||||
|
<div className="grid gap-2">
|
||||||
|
<Label htmlFor="unitPrice">Birim fiyat (₺) *</Label>
|
||||||
|
<Input
|
||||||
|
id="unitPrice"
|
||||||
|
name="unitPrice"
|
||||||
|
type="number"
|
||||||
|
step="0.01"
|
||||||
|
min="0"
|
||||||
|
defaultValue={service?.unitPrice ?? ""}
|
||||||
|
placeholder="0.00"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
{state.fieldErrors?.unitPrice && (
|
||||||
|
<p className="text-destructive text-xs">{state.fieldErrors.unitPrice}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="grid gap-2">
|
||||||
|
<Label htmlFor="billingPeriod">Faturalama dönemi</Label>
|
||||||
|
<Select
|
||||||
|
name="billingPeriod"
|
||||||
|
defaultValue={service?.billingPeriod ?? "onetime"}
|
||||||
|
>
|
||||||
|
<SelectTrigger id="billingPeriod">
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="onetime">Tek seferlik</SelectItem>
|
||||||
|
<SelectItem value="monthly">Aylık</SelectItem>
|
||||||
|
<SelectItem value="yearly">Yıllık</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between rounded-md border p-3">
|
||||||
|
<div className="grid gap-0.5">
|
||||||
|
<Label htmlFor="recurring" className="cursor-pointer">
|
||||||
|
Tekrarlayan hizmet
|
||||||
|
</Label>
|
||||||
|
<p className="text-muted-foreground text-xs">
|
||||||
|
Bu hizmet düzenli olarak fatura kesilecek mi?
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Switch id="recurring" name="recurring" defaultChecked={service?.recurring} />
|
||||||
|
</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" : "Kaydet"}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</SheetFooter>
|
||||||
|
</form>
|
||||||
|
</SheetContent>
|
||||||
|
</Sheet>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,308 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useMemo, useState } from "react";
|
||||||
|
import {
|
||||||
|
type ColumnDef,
|
||||||
|
type SortingState,
|
||||||
|
flexRender,
|
||||||
|
getCoreRowModel,
|
||||||
|
getFilteredRowModel,
|
||||||
|
getPaginationRowModel,
|
||||||
|
getSortedRowModel,
|
||||||
|
useReactTable,
|
||||||
|
} from "@tanstack/react-table";
|
||||||
|
import {
|
||||||
|
ArrowUpDown,
|
||||||
|
Briefcase,
|
||||||
|
ChevronLeft,
|
||||||
|
ChevronRight,
|
||||||
|
MoreHorizontal,
|
||||||
|
Pencil,
|
||||||
|
Plus,
|
||||||
|
Repeat,
|
||||||
|
Search,
|
||||||
|
Trash2,
|
||||||
|
} from "lucide-react";
|
||||||
|
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Card, CardContent } from "@/components/ui/card";
|
||||||
|
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 { BILLING_PERIOD_LABEL, formatTRY } from "@/lib/format";
|
||||||
|
|
||||||
|
import { ServiceFormSheet } from "./service-form-sheet";
|
||||||
|
import { DeleteServiceDialog } from "./delete-service-dialog";
|
||||||
|
import type { CustomerOption, ServiceRow } from "./types";
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
services: ServiceRow[];
|
||||||
|
customers: CustomerOption[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export function ServicesClient({ services, customers }: Props) {
|
||||||
|
const [globalFilter, setGlobalFilter] = useState("");
|
||||||
|
const [sorting, setSorting] = useState<SortingState>([]);
|
||||||
|
const [formOpen, setFormOpen] = useState(false);
|
||||||
|
const [editing, setEditing] = useState<ServiceRow | null>(null);
|
||||||
|
const [deleting, setDeleting] = useState<ServiceRow | null>(null);
|
||||||
|
|
||||||
|
const columns = useMemo<ColumnDef<ServiceRow>[]>(
|
||||||
|
() => [
|
||||||
|
{
|
||||||
|
accessorKey: "name",
|
||||||
|
header: ({ column }) => (
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="-ml-3 h-8"
|
||||||
|
onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
|
||||||
|
>
|
||||||
|
Hizmet
|
||||||
|
<ArrowUpDown className="ml-2 size-3.5" />
|
||||||
|
</Button>
|
||||||
|
),
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<div className="flex flex-col">
|
||||||
|
<span className="font-medium">{row.original.name}</span>
|
||||||
|
{row.original.description && (
|
||||||
|
<span className="text-muted-foreground line-clamp-1 text-xs">
|
||||||
|
{row.original.description}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "customerName",
|
||||||
|
header: "Müşteri",
|
||||||
|
cell: ({ row }) => <span className="text-muted-foreground">{row.original.customerName}</span>,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "unitPrice",
|
||||||
|
header: ({ column }) => (
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="-ml-3 h-8"
|
||||||
|
onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
|
||||||
|
>
|
||||||
|
Fiyat
|
||||||
|
<ArrowUpDown className="ml-2 size-3.5" />
|
||||||
|
</Button>
|
||||||
|
),
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<span className="font-medium">{formatTRY(row.original.unitPrice)}</span>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "billingPeriod",
|
||||||
|
header: "Dönem",
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<div className="flex items-center gap-1.5">
|
||||||
|
<Badge variant="outline">{BILLING_PERIOD_LABEL[row.original.billingPeriod]}</Badge>
|
||||||
|
{row.original.recurring && (
|
||||||
|
<Repeat className="text-muted-foreground size-3.5" aria-label="Tekrarlayan" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "actions",
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<div className="flex justify-end">
|
||||||
|
<DropdownMenu>
|
||||||
|
<DropdownMenuTrigger asChild>
|
||||||
|
<Button variant="ghost" size="icon" className="size-8">
|
||||||
|
<MoreHorizontal className="size-4" />
|
||||||
|
</Button>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent align="end">
|
||||||
|
<DropdownMenuItem
|
||||||
|
onClick={() => {
|
||||||
|
setEditing(row.original);
|
||||||
|
setFormOpen(true);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Pencil className="size-3.5" />
|
||||||
|
Düzenle
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem
|
||||||
|
variant="destructive"
|
||||||
|
onClick={() => setDeleting(row.original)}
|
||||||
|
>
|
||||||
|
<Trash2 className="size-3.5" />
|
||||||
|
Sil
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
|
||||||
|
const table = useReactTable({
|
||||||
|
data: services,
|
||||||
|
columns,
|
||||||
|
state: { globalFilter, sorting },
|
||||||
|
onGlobalFilterChange: setGlobalFilter,
|
||||||
|
onSortingChange: setSorting,
|
||||||
|
getCoreRowModel: getCoreRowModel(),
|
||||||
|
getFilteredRowModel: getFilteredRowModel(),
|
||||||
|
getSortedRowModel: getSortedRowModel(),
|
||||||
|
getPaginationRowModel: getPaginationRowModel(),
|
||||||
|
initialState: { pagination: { pageSize: 20 } },
|
||||||
|
globalFilterFn: (row, _id, filterValue) => {
|
||||||
|
const v = String(filterValue).toLowerCase();
|
||||||
|
return [row.original.name, row.original.customerName, row.original.description]
|
||||||
|
.join(" ")
|
||||||
|
.toLowerCase()
|
||||||
|
.includes(v);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<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={globalFilter}
|
||||||
|
onChange={(e) => setGlobalFilter(e.target.value)}
|
||||||
|
placeholder="Hizmet adı, müşteri..."
|
||||||
|
className="pl-9"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
onClick={() => {
|
||||||
|
setEditing(null);
|
||||||
|
setFormOpen(true);
|
||||||
|
}}
|
||||||
|
disabled={customers.length === 0}
|
||||||
|
>
|
||||||
|
<Plus className="size-4" />
|
||||||
|
Yeni hizmet
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
{table.getHeaderGroups().map((headerGroup) => (
|
||||||
|
<TableRow key={headerGroup.id}>
|
||||||
|
{headerGroup.headers.map((header) => (
|
||||||
|
<TableHead key={header.id}>
|
||||||
|
{header.isPlaceholder
|
||||||
|
? null
|
||||||
|
: flexRender(header.column.columnDef.header, header.getContext())}
|
||||||
|
</TableHead>
|
||||||
|
))}
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{table.getRowModel().rows.length ? (
|
||||||
|
table.getRowModel().rows.map((row) => (
|
||||||
|
<TableRow key={row.id}>
|
||||||
|
{row.getVisibleCells().map((cell) => (
|
||||||
|
<TableCell key={cell.id}>
|
||||||
|
{flexRender(cell.column.columnDef.cell, cell.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">
|
||||||
|
<Briefcase className="size-6" />
|
||||||
|
<p className="text-sm">
|
||||||
|
{customers.length === 0
|
||||||
|
? "Önce bir müşteri ekleyin, sonra hizmet tanımlayabilirsiniz."
|
||||||
|
: "Henüz hizmet eklenmemiş."}
|
||||||
|
</p>
|
||||||
|
{customers.length > 0 && (
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => {
|
||||||
|
setEditing(null);
|
||||||
|
setFormOpen(true);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Plus className="size-3.5" />
|
||||||
|
İlk hizmeti ekle
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</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} hizmet
|
||||||
|
</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>
|
||||||
|
|
||||||
|
<ServiceFormSheet
|
||||||
|
open={formOpen}
|
||||||
|
onOpenChange={(v) => {
|
||||||
|
setFormOpen(v);
|
||||||
|
if (!v) setEditing(null);
|
||||||
|
}}
|
||||||
|
service={editing}
|
||||||
|
customers={customers}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<DeleteServiceDialog
|
||||||
|
open={Boolean(deleting)}
|
||||||
|
onOpenChange={(v) => !v && setDeleting(null)}
|
||||||
|
id={deleting?.id ?? null}
|
||||||
|
name={deleting?.name ?? ""}
|
||||||
|
/>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
export type ServiceRow = {
|
||||||
|
id: string;
|
||||||
|
customerId: string;
|
||||||
|
customerName: string;
|
||||||
|
name: string;
|
||||||
|
description: string;
|
||||||
|
unitPrice: number;
|
||||||
|
recurring: boolean;
|
||||||
|
billingPeriod: "monthly" | "yearly" | "onetime";
|
||||||
|
createdAt: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type CustomerOption = { id: string; name: string };
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import type { Metadata } from "next";
|
||||||
|
import { redirect } from "next/navigation";
|
||||||
|
|
||||||
|
import { listCustomers } from "@/lib/appwrite/customer-queries";
|
||||||
|
import { listServices } from "@/lib/appwrite/service-queries";
|
||||||
|
import { requireTenant } from "@/lib/appwrite/tenant-guard";
|
||||||
|
import { ServicesClient } from "./components/services-client";
|
||||||
|
|
||||||
|
export const metadata: Metadata = {
|
||||||
|
title: "İşletmem — Hizmetler",
|
||||||
|
};
|
||||||
|
|
||||||
|
export default async function ServicesPage() {
|
||||||
|
let ctx;
|
||||||
|
try {
|
||||||
|
ctx = await requireTenant();
|
||||||
|
} catch {
|
||||||
|
redirect("/onboarding");
|
||||||
|
}
|
||||||
|
|
||||||
|
const [services, customers] = await Promise.all([
|
||||||
|
listServices(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">Hizmetler</h1>
|
||||||
|
<p className="text-muted-foreground text-sm">
|
||||||
|
Müşterilere sunduğunuz hizmetleri ve fiyatlarını yönetin.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ServicesClient
|
||||||
|
services={services.map((s) => ({
|
||||||
|
id: s.$id,
|
||||||
|
customerId: s.customerId,
|
||||||
|
customerName: customerMap.get(s.customerId) ?? "—",
|
||||||
|
name: s.name,
|
||||||
|
description: s.description ?? "",
|
||||||
|
unitPrice: s.unitPrice,
|
||||||
|
recurring: Boolean(s.recurring),
|
||||||
|
billingPeriod: s.billingPeriod ?? "onetime",
|
||||||
|
createdAt: s.$createdAt,
|
||||||
|
}))}
|
||||||
|
customers={customers.map((c) => ({ id: c.$id, name: c.name }))}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,185 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { AppwriteException, ID, Permission, Role } from "node-appwrite";
|
||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
import { logAudit } from "./audit";
|
||||||
|
import { DATABASE_ID, TABLES, type Service } from "./schema";
|
||||||
|
import { createAdminClient } from "./server";
|
||||||
|
import { requireTenant } from "./tenant-guard";
|
||||||
|
import type { ServiceActionState } from "./service-types";
|
||||||
|
import { serviceSchema } from "@/lib/validation/services";
|
||||||
|
|
||||||
|
function appwriteError(e: unknown): string {
|
||||||
|
if (e instanceof AppwriteException) {
|
||||||
|
return e.message || "Beklenmeyen bir hata oluştu.";
|
||||||
|
}
|
||||||
|
return "Bağlantı hatası. Tekrar deneyin.";
|
||||||
|
}
|
||||||
|
|
||||||
|
function pickFormFields(formData: FormData) {
|
||||||
|
return {
|
||||||
|
customerId: String(formData.get("customerId") ?? ""),
|
||||||
|
name: String(formData.get("name") ?? "").trim(),
|
||||||
|
description: String(formData.get("description") ?? "").trim(),
|
||||||
|
unitPrice: String(formData.get("unitPrice") ?? "0"),
|
||||||
|
recurring: formData.get("recurring") ?? false,
|
||||||
|
billingPeriod: (formData.get("billingPeriod") as "monthly" | "yearly" | "onetime" | null) ??
|
||||||
|
"onetime",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
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")),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createServiceAction(
|
||||||
|
_prev: ServiceActionState,
|
||||||
|
formData: FormData,
|
||||||
|
): Promise<ServiceActionState> {
|
||||||
|
let ctx;
|
||||||
|
try {
|
||||||
|
ctx = await requireTenant();
|
||||||
|
} catch {
|
||||||
|
return { ok: false, error: "Yetkiniz yok." };
|
||||||
|
}
|
||||||
|
|
||||||
|
const parsed = serviceSchema.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.services,
|
||||||
|
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: "service",
|
||||||
|
entityId: row.$id,
|
||||||
|
changes: parsed.data,
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
return { ok: false, error: appwriteError(e) };
|
||||||
|
}
|
||||||
|
|
||||||
|
revalidatePath("/services");
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateServiceAction(
|
||||||
|
_prev: ServiceActionState,
|
||||||
|
formData: FormData,
|
||||||
|
): Promise<ServiceActionState> {
|
||||||
|
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 = serviceSchema.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.services,
|
||||||
|
id,
|
||||||
|
)) as unknown as Service;
|
||||||
|
|
||||||
|
if (existing.tenantId !== ctx.tenantId) {
|
||||||
|
return { ok: false, error: "Erişim engellendi." };
|
||||||
|
}
|
||||||
|
|
||||||
|
await tablesDB.updateRow(DATABASE_ID, TABLES.services, id, parsed.data);
|
||||||
|
|
||||||
|
await logAudit({
|
||||||
|
tenantId: ctx.tenantId,
|
||||||
|
userId: ctx.user.id,
|
||||||
|
action: "update",
|
||||||
|
entityType: "service",
|
||||||
|
entityId: id,
|
||||||
|
changes: parsed.data,
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
return { ok: false, error: appwriteError(e) };
|
||||||
|
}
|
||||||
|
|
||||||
|
revalidatePath("/services");
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteServiceAction(formData: FormData): Promise<ServiceActionState> {
|
||||||
|
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.services,
|
||||||
|
id,
|
||||||
|
)) as unknown as Service;
|
||||||
|
|
||||||
|
if (existing.tenantId !== ctx.tenantId) {
|
||||||
|
return { ok: false, error: "Erişim engellendi." };
|
||||||
|
}
|
||||||
|
|
||||||
|
await tablesDB.deleteRow(DATABASE_ID, TABLES.services, id);
|
||||||
|
|
||||||
|
await logAudit({
|
||||||
|
tenantId: ctx.tenantId,
|
||||||
|
userId: ctx.user.id,
|
||||||
|
action: "delete",
|
||||||
|
entityType: "service",
|
||||||
|
entityId: id,
|
||||||
|
changes: { name: existing.name },
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
return { ok: false, error: appwriteError(e) };
|
||||||
|
}
|
||||||
|
|
||||||
|
revalidatePath("/services");
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
import "server-only";
|
||||||
|
|
||||||
|
import { Query } from "node-appwrite";
|
||||||
|
|
||||||
|
import { createAdminClient } from "./server";
|
||||||
|
import { DATABASE_ID, TABLES, type Service } from "./schema";
|
||||||
|
|
||||||
|
export async function listServices(tenantId: string): Promise<Service[]> {
|
||||||
|
try {
|
||||||
|
const { tablesDB } = createAdminClient();
|
||||||
|
const result = await tablesDB.listRows({
|
||||||
|
databaseId: DATABASE_ID,
|
||||||
|
tableId: TABLES.services,
|
||||||
|
queries: [
|
||||||
|
Query.equal("tenantId", tenantId),
|
||||||
|
Query.orderDesc("$createdAt"),
|
||||||
|
Query.limit(500),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
return result.rows as unknown as Service[];
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listServicesByCustomer(
|
||||||
|
tenantId: string,
|
||||||
|
customerId: string,
|
||||||
|
): Promise<Service[]> {
|
||||||
|
try {
|
||||||
|
const { tablesDB } = createAdminClient();
|
||||||
|
const result = await tablesDB.listRows({
|
||||||
|
databaseId: DATABASE_ID,
|
||||||
|
tableId: TABLES.services,
|
||||||
|
queries: [
|
||||||
|
Query.equal("tenantId", tenantId),
|
||||||
|
Query.equal("customerId", customerId),
|
||||||
|
Query.orderDesc("$createdAt"),
|
||||||
|
Query.limit(500),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
return result.rows as unknown as Service[];
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
export type ServiceActionState = {
|
||||||
|
ok: boolean;
|
||||||
|
error?: string;
|
||||||
|
fieldErrors?: Record<string, string>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const initialServiceState: ServiceActionState = { ok: false };
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
export function formatTRY(amount: number): string {
|
||||||
|
return new Intl.NumberFormat("tr-TR", {
|
||||||
|
style: "currency",
|
||||||
|
currency: "TRY",
|
||||||
|
minimumFractionDigits: 2,
|
||||||
|
maximumFractionDigits: 2,
|
||||||
|
}).format(amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatDate(iso: string | undefined | null): string {
|
||||||
|
if (!iso) return "—";
|
||||||
|
return new Date(iso).toLocaleDateString("tr-TR", {
|
||||||
|
day: "2-digit",
|
||||||
|
month: "short",
|
||||||
|
year: "numeric",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatDateTime(iso: string | undefined | null): string {
|
||||||
|
if (!iso) return "—";
|
||||||
|
return new Date(iso).toLocaleString("tr-TR", {
|
||||||
|
day: "2-digit",
|
||||||
|
month: "short",
|
||||||
|
year: "numeric",
|
||||||
|
hour: "2-digit",
|
||||||
|
minute: "2-digit",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export const BILLING_PERIOD_LABEL: Record<string, string> = {
|
||||||
|
monthly: "Aylık",
|
||||||
|
yearly: "Yıllık",
|
||||||
|
onetime: "Tek seferlik",
|
||||||
|
};
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
export const serviceSchema = z.object({
|
||||||
|
customerId: z.string().min(1, "Müşteri seçin."),
|
||||||
|
name: z.string().trim().min(1, "Hizmet adı zorunlu.").max(255),
|
||||||
|
description: z
|
||||||
|
.string()
|
||||||
|
.trim()
|
||||||
|
.max(2000)
|
||||||
|
.optional()
|
||||||
|
.transform((v) => (v ? v : undefined)),
|
||||||
|
unitPrice: z
|
||||||
|
.union([z.number(), z.string()])
|
||||||
|
.transform((v) => (typeof v === "string" ? Number(v.replace(",", ".")) : v))
|
||||||
|
.pipe(z.number().nonnegative("Negatif olamaz.")),
|
||||||
|
recurring: z
|
||||||
|
.union([z.boolean(), z.literal("on"), z.literal(""), z.undefined()])
|
||||||
|
.transform((v) => v === true || v === "on")
|
||||||
|
.optional(),
|
||||||
|
billingPeriod: z.enum(["monthly", "yearly", "onetime"]).optional().default("onetime"),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type ServiceInput = z.infer<typeof serviceSchema>;
|
||||||
Reference in New Issue
Block a user