"use client"; import { useState } from "react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { toast } from "sonner"; import { Button, Select, EmptyState } from "@/components/ds"; import { crmApi } from "@/modules/crm/services/crm-api"; import { useTenantId } from "@/hooks/useTenantId"; import { CrmPageLoader, CrmPageError } from "@/modules/crm/pages/shared"; import { CrmBreadcrumbs } from "@/modules/crm/components/CrmBreadcrumbs"; import { PageHeader } from "@/components/ds"; import type { Opportunity, PipelineStage } from "@/modules/crm/types"; import { cn } from "@/lib/utils"; export default function KanbanPage() { const { tenantId } = useTenantId(); const qc = useQueryClient(); const [pipelineId, setPipelineId] = useState(""); const pipelinesQ = useQuery({ queryKey: ["crm", tenantId, "pipelines"], queryFn: () => crmApi.pipelines.list(tenantId!, { page: 1, page_size: 100 }), enabled: !!tenantId, }); const activePipeline = pipelineId || pipelinesQ.data?.[0]?.id || ""; const stagesQ = useQuery({ queryKey: ["crm", tenantId, "stages", activePipeline], queryFn: () => crmApi.pipelines.stages(tenantId!, activePipeline, { page: 1, page_size: 100 }), enabled: !!tenantId && !!activePipeline, }); const oppsQ = useQuery({ queryKey: ["crm", tenantId, "opportunities"], queryFn: () => crmApi.opportunities.list(tenantId!, { page: 1, page_size: 500 }), enabled: !!tenantId, }); const moveM = useMutation({ mutationFn: ({ id, stageId }: { id: string; stageId: string }) => crmApi.opportunities.changeStage(tenantId!, id, { stage_id: stageId }), onSuccess: async () => { toast.success("مرحله به‌روز شد"); await qc.invalidateQueries({ queryKey: ["crm", tenantId, "opportunities"] }); }, onError: (e: Error) => toast.error(e.message), }); if (!tenantId || pipelinesQ.isLoading) return ; if (pipelinesQ.error) return pipelinesQ.refetch()} />; const stages = (stagesQ.data ?? []).sort((a, b) => a.position - b.position); const opps = (oppsQ.data ?? []).filter( (o) => !activePipeline || o.pipeline_id === activePipeline ); const byStage = (stageId: string) => opps.filter((o) => o.stage_id === stageId); return (
setPipelineId(e.target.value)} className="min-w-[180px]" > {(pipelinesQ.data ?? []).map((p) => ( ))} } /> {!stages.length ? ( ) : (
{stages.map((stage: PipelineStage) => (

{stage.name}

{byStage(stage.id).length}
{byStage(stage.id).map((deal: Opportunity) => (

{deal.title ?? deal.name}

{deal.amount} {deal.currency_code}

{stages .filter((s) => s.id !== stage.id) .slice(0, 3) .map((s) => ( ))}
))}
))}
)}
); }