feat: services — preset names, currency, multi-assignee (MCP: assigneeIds+currency columns)

This commit is contained in:
kovakmedya
2026-05-01 02:52:09 +03:00
parent 591df8f82e
commit 9e1355a137
8 changed files with 224 additions and 25 deletions
@@ -1,12 +1,19 @@
"use client"; "use client";
import { useActionState, useEffect } from "react"; import { useActionState, useEffect, useState } from "react";
import { Loader2, Save } from "lucide-react"; import { Check, ChevronDown, Loader2, Save, Users } from "lucide-react";
import { toast } from "sonner"; import { toast } from "sonner";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label"; import { Label } from "@/components/ui/label";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { import {
Select, Select,
SelectContent, SelectContent,
@@ -24,12 +31,32 @@ import {
} from "@/components/ui/sheet"; } from "@/components/ui/sheet";
import { Switch } from "@/components/ui/switch"; import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea"; import { Textarea } from "@/components/ui/textarea";
import { cn } from "@/lib/utils";
import { import {
createServiceAction, createServiceAction,
updateServiceAction, updateServiceAction,
} from "@/lib/appwrite/service-actions"; } from "@/lib/appwrite/service-actions";
import { initialServiceState } from "@/lib/appwrite/service-types"; import { initialServiceState } from "@/lib/appwrite/service-types";
import type { CustomerOption, ServiceRow } from "./types"; import type { CustomerOption, MemberOption, ServiceRow } from "./types";
const PRESET_SERVICES = [
"Web sitesi tasarımı",
"Web sitesi bakımı",
"SEO optimizasyonu",
"Sosyal medya yönetimi",
"Domain kayıt / yenileme",
"Hosting hizmeti",
"Kurumsal e-posta",
"Grafik tasarım",
"Logo tasarımı",
"Google Ads yönetimi",
"Meta Ads yönetimi",
"Yazılım geliştirme",
"Mobil uygulama",
"Teknik destek",
"Muhasebe danışmanlığı",
"Eğitim / danışmanlık",
];
type Props = { type Props = {
open: boolean; open: boolean;
@@ -37,6 +64,7 @@ type Props = {
service?: ServiceRow | null; service?: ServiceRow | null;
customers: CustomerOption[]; customers: CustomerOption[];
defaultCustomerId?: string; defaultCustomerId?: string;
members: MemberOption[];
}; };
export function ServiceFormSheet({ export function ServiceFormSheet({
@@ -45,11 +73,24 @@ export function ServiceFormSheet({
service, service,
customers, customers,
defaultCustomerId, defaultCustomerId,
members,
}: Props) { }: Props) {
const isEdit = Boolean(service); const isEdit = Boolean(service);
const action = isEdit ? updateServiceAction : createServiceAction; const action = isEdit ? updateServiceAction : createServiceAction;
const [state, formAction, isPending] = useActionState(action, initialServiceState); const [state, formAction, isPending] = useActionState(action, initialServiceState);
const [name, setName] = useState(service?.name ?? "");
const [assigneeIds, setAssigneeIds] = useState<string[]>(service?.assigneeIds ?? []);
const [assigneeOpen, setAssigneeOpen] = useState(false);
// Reset local state when sheet opens with a different service
useEffect(() => {
if (open) {
setName(service?.name ?? "");
setAssigneeIds(service?.assigneeIds ?? []);
}
}, [open, service]);
useEffect(() => { useEffect(() => {
if (state.ok) { if (state.ok) {
toast.success(isEdit ? "Hizmet güncellendi." : "Hizmet eklendi."); toast.success(isEdit ? "Hizmet güncellendi." : "Hizmet eklendi.");
@@ -60,6 +101,12 @@ export function ServiceFormSheet({
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [state]); }, [state]);
const toggleAssignee = (id: string) => {
setAssigneeIds((prev) =>
prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id],
);
};
return ( return (
<Sheet open={open} onOpenChange={onOpenChange}> <Sheet open={open} onOpenChange={onOpenChange}>
<SheetContent className="flex w-full flex-col gap-0 p-0 sm:max-w-xl"> <SheetContent className="flex w-full flex-col gap-0 p-0 sm:max-w-xl">
@@ -74,8 +121,13 @@ export function ServiceFormSheet({
<form action={formAction} className="flex flex-1 flex-col"> <form action={formAction} className="flex flex-1 flex-col">
{isEdit && service && <input type="hidden" name="id" value={service.id} />} {isEdit && service && <input type="hidden" name="id" value={service.id} />}
{/* Assignee hidden inputs — one per selected member */}
{assigneeIds.map((id) => (
<input key={id} type="hidden" name="assigneeIds" value={id} />
))}
<div className="flex-1 space-y-4 overflow-y-auto px-6 py-5"> <div className="flex-1 space-y-5 overflow-y-auto px-6 py-5">
{/* Müşteri */}
<div className="grid gap-2"> <div className="grid gap-2">
<Label htmlFor="customerId">Müşteri *</Label> <Label htmlFor="customerId">Müşteri *</Label>
<Select <Select
@@ -99,13 +151,33 @@ export function ServiceFormSheet({
)} )}
</div> </div>
{/* Hizmet adı + hazır şablonlar */}
<div className="grid gap-2"> <div className="grid gap-2">
<Label htmlFor="name">Hizmet adı *</Label> <Label htmlFor="name">Hizmet adı *</Label>
{/* Preset chips */}
<div className="flex flex-wrap gap-1.5">
{PRESET_SERVICES.map((preset) => (
<button
key={preset}
type="button"
onClick={() => setName(preset)}
className={cn(
"rounded-full border px-2.5 py-0.5 text-xs transition-colors",
name === preset
? "border-primary bg-primary text-primary-foreground"
: "border-border bg-muted/40 text-muted-foreground hover:border-primary/50 hover:text-foreground",
)}
>
{preset}
</button>
))}
</div>
<Input <Input
id="name" id="name"
name="name" name="name"
defaultValue={service?.name ?? ""} value={name}
placeholder="Örn. Web hosting bakımı" onChange={(e) => setName(e.target.value)}
placeholder="Hizmet adını yazın veya yukarıdan seçin"
required required
/> />
{state.fieldErrors?.name && ( {state.fieldErrors?.name && (
@@ -113,6 +185,7 @@ export function ServiceFormSheet({
)} )}
</div> </div>
{/* Açıklama */}
<div className="grid gap-2"> <div className="grid gap-2">
<Label htmlFor="description">Açıklama</Label> <Label htmlFor="description">Açıklama</Label>
<Textarea <Textarea
@@ -124,9 +197,10 @@ export function ServiceFormSheet({
/> />
</div> </div>
<div className="grid gap-4 md:grid-cols-2"> {/* Fiyat + Para birimi */}
<div className="grid gap-2"> <div className="grid gap-4 sm:grid-cols-3">
<Label htmlFor="unitPrice">Birim fiyat () *</Label> <div className="grid gap-2 sm:col-span-2">
<Label htmlFor="unitPrice">Birim fiyat *</Label>
<Input <Input
id="unitPrice" id="unitPrice"
name="unitPrice" name="unitPrice"
@@ -141,6 +215,23 @@ export function ServiceFormSheet({
<p className="text-destructive text-xs">{state.fieldErrors.unitPrice}</p> <p className="text-destructive text-xs">{state.fieldErrors.unitPrice}</p>
)} )}
</div> </div>
<div className="grid gap-2">
<Label htmlFor="currency">Para birimi</Label>
<Select name="currency" defaultValue={service?.currency ?? "TRY"}>
<SelectTrigger id="currency">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="TRY"> TRY</SelectItem>
<SelectItem value="USD">$ USD</SelectItem>
<SelectItem value="EUR"> EUR</SelectItem>
</SelectContent>
</Select>
</div>
</div>
{/* Faturalama dönemi + Tekrarlayan */}
<div className="grid gap-4 sm:grid-cols-2">
<div className="grid gap-2"> <div className="grid gap-2">
<Label htmlFor="billingPeriod">Faturalama dönemi</Label> <Label htmlFor="billingPeriod">Faturalama dönemi</Label>
<Select <Select
@@ -157,19 +248,74 @@ export function ServiceFormSheet({
</SelectContent> </SelectContent>
</Select> </Select>
</div> </div>
<div className="flex items-end pb-0.5">
<div className="flex w-full items-center justify-between rounded-md border p-3">
<Label htmlFor="recurring" className="cursor-pointer text-sm">
Tekrarlayan
</Label>
<Switch
id="recurring"
name="recurring"
defaultChecked={service?.recurring}
/>
</div>
</div>
</div> </div>
<div className="flex items-center justify-between rounded-md border p-3"> {/* Sorumlu personel */}
<div className="grid gap-0.5"> {members.length > 0 && (
<Label htmlFor="recurring" className="cursor-pointer"> <div className="grid gap-2">
Tekrarlayan hizmet <Label>Sorumlu personel</Label>
</Label> <Popover open={assigneeOpen} onOpenChange={setAssigneeOpen}>
<p className="text-muted-foreground text-xs"> <PopoverTrigger asChild>
Bu hizmet düzenli olarak fatura kesilecek mi? <Button
</p> type="button"
variant="outline"
className="h-auto min-h-10 w-full justify-between px-3 py-2"
>
<div className="flex flex-wrap gap-1">
{assigneeIds.length === 0 ? (
<span className="text-muted-foreground text-sm font-normal">
Personel seçin (isteğe bağlı)
</span>
) : (
assigneeIds.map((id) => {
const m = members.find((x) => x.id === id);
return (
<Badge key={id} variant="secondary" className="font-normal">
{m?.name ?? id}
</Badge>
);
})
)}
</div> </div>
<Switch id="recurring" name="recurring" defaultChecked={service?.recurring} /> <ChevronDown className="text-muted-foreground ml-2 size-4 shrink-0" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-64 p-1" align="start">
{members.map((m) => {
const checked = assigneeIds.includes(m.id);
return (
<label
key={m.id}
className="flex cursor-pointer items-center gap-3 rounded px-3 py-2 hover:bg-muted"
>
<Checkbox
checked={checked}
onCheckedChange={() => toggleAssignee(m.id)}
/>
<div className="flex-1 min-w-0">
<div className="truncate text-sm font-medium">{m.name}</div>
<div className="text-muted-foreground truncate text-xs">{m.email}</div>
</div> </div>
{checked && <Check className="text-primary size-3.5 shrink-0" />}
</label>
);
})}
</PopoverContent>
</Popover>
</div>
)}
</div> </div>
<SheetFooter className="border-t bg-muted/30 px-6 pt-4"> <SheetFooter className="border-t bg-muted/30 px-6 pt-4">
@@ -42,18 +42,20 @@ import {
TableHeader, TableHeader,
TableRow, TableRow,
} from "@/components/ui/table"; } from "@/components/ui/table";
import { BILLING_PERIOD_LABEL, formatTRY } from "@/lib/format"; import { BILLING_PERIOD_LABEL, formatCurrency } from "@/lib/format";
import { ServiceFormSheet } from "./service-form-sheet"; import { ServiceFormSheet } from "./service-form-sheet";
import { DeleteServiceDialog } from "./delete-service-dialog"; import { DeleteServiceDialog } from "./delete-service-dialog";
import type { CustomerOption, ServiceRow } from "./types"; import type { CustomerOption, MemberOption, ServiceRow } from "./types";
type Props = { type Props = {
services: ServiceRow[]; services: ServiceRow[];
customers: CustomerOption[]; customers: CustomerOption[];
members: MemberOption[];
}; };
export function ServicesClient({ services, customers }: Props) { export function ServicesClient({ services, customers, members }: Props) {
const memberMap = useMemo(() => new Map(members.map((m) => [m.id, m.name])), [members]);
const [globalFilter, setGlobalFilter] = useState(""); const [globalFilter, setGlobalFilter] = useState("");
const [sorting, setSorting] = useState<SortingState>([]); const [sorting, setSorting] = useState<SortingState>([]);
const [formOpen, setFormOpen] = useState(false); const [formOpen, setFormOpen] = useState(false);
@@ -105,7 +107,9 @@ export function ServicesClient({ services, customers }: Props) {
</Button> </Button>
), ),
cell: ({ row }) => ( cell: ({ row }) => (
<span className="font-medium">{formatTRY(row.original.unitPrice)}</span> <span className="font-medium">
{formatCurrency(row.original.unitPrice, row.original.currency)}
</span>
), ),
}, },
{ {
@@ -120,6 +124,25 @@ export function ServicesClient({ services, customers }: Props) {
</div> </div>
), ),
}, },
{
id: "assignees",
header: "Personel",
cell: ({ row }) => {
const names = row.original.assigneeIds
.map((id) => memberMap.get(id))
.filter(Boolean) as string[];
if (names.length === 0) return <span className="text-muted-foreground text-xs"></span>;
return (
<div className="flex flex-wrap gap-1">
{names.map((n) => (
<Badge key={n} variant="secondary" className="text-xs font-normal">
{n}
</Badge>
))}
</div>
);
},
},
{ {
id: "actions", id: "actions",
cell: ({ row }) => ( cell: ({ row }) => (
@@ -169,7 +192,8 @@ export function ServicesClient({ services, customers }: Props) {
initialState: { pagination: { pageSize: 20 } }, initialState: { pagination: { pageSize: 20 } },
globalFilterFn: (row, _id, filterValue) => { globalFilterFn: (row, _id, filterValue) => {
const v = String(filterValue).toLowerCase(); const v = String(filterValue).toLowerCase();
return [row.original.name, row.original.customerName, row.original.description] const assigneeNames = row.original.assigneeIds.map((id) => memberMap.get(id) ?? "").join(" ");
return [row.original.name, row.original.customerName, row.original.description, assigneeNames]
.join(" ") .join(" ")
.toLowerCase() .toLowerCase()
.includes(v); .includes(v);
@@ -295,6 +319,7 @@ export function ServicesClient({ services, customers }: Props) {
}} }}
service={editing} service={editing}
customers={customers} customers={customers}
members={members}
/> />
<DeleteServiceDialog <DeleteServiceDialog
@@ -5,9 +5,13 @@ export type ServiceRow = {
name: string; name: string;
description: string; description: string;
unitPrice: number; unitPrice: number;
currency: string;
recurring: boolean; recurring: boolean;
billingPeriod: "monthly" | "yearly" | "onetime"; billingPeriod: "monthly" | "yearly" | "onetime";
assigneeIds: string[];
createdAt: string; createdAt: string;
}; };
export type CustomerOption = { id: string; name: string }; export type CustomerOption = { id: string; name: string };
export type MemberOption = { id: string; name: string; email: string };
+10 -1
View File
@@ -3,6 +3,7 @@ import { redirect } from "next/navigation";
import { listCustomers } from "@/lib/appwrite/customer-queries"; import { listCustomers } from "@/lib/appwrite/customer-queries";
import { listServices } from "@/lib/appwrite/service-queries"; import { listServices } from "@/lib/appwrite/service-queries";
import { createAdminClient } from "@/lib/appwrite/server";
import { requireTenant } from "@/lib/appwrite/tenant-guard"; import { requireTenant } from "@/lib/appwrite/tenant-guard";
import { ServicesClient } from "./components/services-client"; import { ServicesClient } from "./components/services-client";
@@ -18,12 +19,17 @@ export default async function ServicesPage() {
redirect("/onboarding"); redirect("/onboarding");
} }
const [services, customers] = await Promise.all([ const { teams } = createAdminClient();
const [services, customers, membershipsResult] = await Promise.all([
listServices(ctx.tenantId), listServices(ctx.tenantId),
listCustomers(ctx.tenantId), listCustomers(ctx.tenantId),
teams.listMemberships(ctx.tenantId).catch(() => ({ memberships: [] })),
]); ]);
const customerMap = new Map(customers.map((c) => [c.$id, c.name])); const customerMap = new Map(customers.map((c) => [c.$id, c.name]));
const members = membershipsResult.memberships
.filter((m) => m.confirm)
.map((m) => ({ id: m.userId, name: m.userName || m.userEmail, email: m.userEmail }));
return ( return (
<div className="flex-1 space-y-6 px-6 pt-0"> <div className="flex-1 space-y-6 px-6 pt-0">
@@ -43,11 +49,14 @@ export default async function ServicesPage() {
name: s.name, name: s.name,
description: s.description ?? "", description: s.description ?? "",
unitPrice: s.unitPrice, unitPrice: s.unitPrice,
currency: s.currency ?? "TRY",
recurring: Boolean(s.recurring), recurring: Boolean(s.recurring),
billingPeriod: s.billingPeriod ?? "onetime", billingPeriod: s.billingPeriod ?? "onetime",
assigneeIds: s.assigneeIds ?? [],
createdAt: s.$createdAt, createdAt: s.$createdAt,
}))} }))}
customers={customers.map((c) => ({ id: c.$id, name: c.name }))} customers={customers.map((c) => ({ id: c.$id, name: c.name }))}
members={members}
/> />
</div> </div>
); );
+2
View File
@@ -84,8 +84,10 @@ export interface Service extends Row {
name: string; name: string;
description?: string; description?: string;
unitPrice: number; unitPrice: number;
currency?: string;
recurring?: boolean; recurring?: boolean;
billingPeriod?: BillingPeriod; billingPeriod?: BillingPeriod;
assigneeIds?: string[];
} }
export interface Software extends Row { export interface Software extends Row {
+2
View File
@@ -24,9 +24,11 @@ function pickFormFields(formData: FormData) {
name: String(formData.get("name") ?? "").trim(), name: String(formData.get("name") ?? "").trim(),
description: String(formData.get("description") ?? "").trim(), description: String(formData.get("description") ?? "").trim(),
unitPrice: String(formData.get("unitPrice") ?? "0"), unitPrice: String(formData.get("unitPrice") ?? "0"),
currency: (formData.get("currency") as "TRY" | "USD" | "EUR" | null) ?? "TRY",
recurring: formData.get("recurring") ?? false, recurring: formData.get("recurring") ?? false,
billingPeriod: (formData.get("billingPeriod") as "monthly" | "yearly" | "onetime" | null) ?? billingPeriod: (formData.get("billingPeriod") as "monthly" | "yearly" | "onetime" | null) ??
"onetime", "onetime",
assigneeIds: formData.getAll("assigneeIds").map(String).filter(Boolean),
}; };
} }
+9
View File
@@ -7,6 +7,15 @@ export function formatTRY(amount: number): string {
}).format(amount); }).format(amount);
} }
export function formatCurrency(amount: number, currency = "TRY"): string {
return new Intl.NumberFormat("tr-TR", {
style: "currency",
currency,
minimumFractionDigits: 2,
maximumFractionDigits: 2,
}).format(amount);
}
export function formatDate(iso: string | undefined | null): string { export function formatDate(iso: string | undefined | null): string {
if (!iso) return "—"; if (!iso) return "—";
return new Date(iso).toLocaleDateString("tr-TR", { return new Date(iso).toLocaleDateString("tr-TR", {
+2
View File
@@ -17,7 +17,9 @@ export const serviceSchema = z.object({
.union([z.boolean(), z.literal("on"), z.literal(""), z.undefined()]) .union([z.boolean(), z.literal("on"), z.literal(""), z.undefined()])
.transform((v) => v === true || v === "on") .transform((v) => v === true || v === "on")
.optional(), .optional(),
currency: z.enum(["TRY", "USD", "EUR"]).optional().default("TRY"),
billingPeriod: z.enum(["monthly", "yearly", "onetime"]).optional().default("onetime"), billingPeriod: z.enum(["monthly", "yearly", "onetime"]).optional().default("onetime"),
assigneeIds: z.array(z.string().min(1)).optional().default([]),
}); });
export type ServiceInput = z.infer<typeof serviceSchema>; export type ServiceInput = z.infer<typeof serviceSchema>;