import { useState } from "react"; import { useClient } from "urql"; import { graphql, type ResultOf, type VariablesOf } from "@/graphql"; import { useToast } from "@/hooks/use-toast"; import { fetchAllPages } from "@/lib/fetch-all-pages"; import { toDateInputValue } from "@/lib/format-date"; import { csvTimestamp, downloadCsv, toCsv, type CsvColumn } from "@/lib/to-csv"; /** CSV export for the Companies dashboard (issue #605). */ const CompaniesCsvQuery = graphql(` query CompaniesCsv( $first: Int $after: String $order: [CompanyOrderInput] $query: CompanyQueryInput ) { companies(first: $first, after: $after, order: $order, query: $query) { pageInfo { hasNextPage endCursor } edges { node { legalName taxId status createdAt baseCurrency { code } } } } } `); type CsvVariables = VariablesOf; type CsvResult = ResultOf; type CompanyCsvRow = NonNullable["edges"]>[number]["node"]; const columns: CsvColumn[] = [ { header: "Legal Name", value: (r) => r.legalName }, { header: "Tax ID", value: (r) => r.taxId }, { header: "Base Currency", value: (r) => r.baseCurrency?.code }, { header: "Status", value: (r) => r.status }, { header: "Created Date", value: (r) => toDateInputValue(r.createdAt) }, ]; export function useExportCompaniesCsv() { const client = useClient(); const toast = useToast(); const [isExporting, setIsExporting] = useState(false); async function exportCsv(order: CsvVariables["order"], query: CsvVariables["query"]) { if (isExporting) return; setIsExporting(true); try { const rows = await fetchAllPages( client, CompaniesCsvQuery, { order, query }, (d) => d.companies, ); if (rows.length === 0) { toast.error("No companies to export"); return; } downloadCsv(toCsv(rows, columns), `companies-${csvTimestamp()}.csv`); toast.success(`${rows.length.toLocaleString()} rows exported`); } catch (err) { console.error("CSV export failed:", err); toast.error("Failed to export CSV"); } finally { setIsExporting(false); } } return { exportCsv, isExporting }; }