"use client"; import { useState } from "react"; import { useForm } from "react-hook-form"; import { z } from "zod"; import { zodResolver } from "@hookform/resolvers/zod"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { toast } from "sonner"; import { Plus } from "lucide-react"; import { beautyBusinessApi, type Branch } from "@/modules/beauty/services/beauty-business-api"; import { useTenantId } from "@/hooks/useTenantId"; import { PageHeader, Button, Dialog, Input, DataTable, EmptyState, LoadingState, ErrorState, Badge, FormField, Select, } from "@/components/ds"; const createSchema = z.object({ organization_id: z.string().min(1, "سازمان الزامی است"), code: z.string().min(1, "کد الزامی است"), name: z.string().min(1, "نام الزامی است"), description: z.string().optional(), }); const statusLabel: Record = { draft: "پیش‌نویس", active: "فعال", inactive: "غیرفعال", suspended: "معلق", archived: "آرشیو", }; export default function BranchesPage() { const { tenantId } = useTenantId(); const qc = useQueryClient(); const [createOpen, setCreateOpen] = useState(false); const orgsQ = useQuery({ queryKey: ["beauty", tenantId, "organizations"], queryFn: () => beautyBusinessApi.organizations.list(tenantId!), enabled: !!tenantId, }); const listQ = useQuery({ queryKey: ["beauty", tenantId, "branches"], queryFn: () => beautyBusinessApi.branches.list(tenantId!), enabled: !!tenantId, }); const createForm = useForm>({ resolver: zodResolver(createSchema), defaultValues: { organization_id: "", code: "", name: "", description: "" }, }); const invalidate = () => qc.invalidateQueries({ queryKey: ["beauty", tenantId, "branches"] }); const createM = useMutation({ mutationFn: (d: z.infer) => beautyBusinessApi.branches.create(tenantId!, d), onSuccess: async () => { toast.success("شعبه ایجاد شد"); setCreateOpen(false); createForm.reset(); await invalidate(); }, onError: (e: Error) => toast.error(e.message), }); if (!tenantId || listQ.isLoading || orgsQ.isLoading) return ; if (listQ.error) { return listQ.refetch()} />; } const orgMap = Object.fromEntries((orgsQ.data ?? []).map((o) => [o.id, o.name])); return (
setCreateOpen(true)} disabled={(orgsQ.data?.length ?? 0) === 0}> شعبه جدید } /> {(orgsQ.data?.length ?? 0) === 0 ? ( ) : ( orgMap[String(r.organization_id)] ?? "—", }, { key: "status", header: "وضعیت", render: (r) => ( {statusLabel[String(r.status)] ?? String(r.status)} ), }, ]} rows={(listQ.data ?? []) as unknown as Record[]} empty={ setCreateOpen(true)}>ایجاد شعبه} />} /> )} setCreateOpen(false)} title="شعبه جدید">
createM.mutate(d))}>
); }