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 { csvTimestamp, downloadCsv, toCsv, type CsvColumn } from "@/lib/to-csv"; /** CSV export for the Users dashboard (issue #605). */ const UsersCsvQuery = graphql(` query UsersCsv($first: Int, $after: String, $order: [UserOrderInput], $query: UserQueryInput) { users(first: $first, after: $after, order: $order, query: $query) { pageInfo { hasNextPage endCursor } edges { node { name email status userRoles { edges { node { role { name } } } } } } } } `); type CsvVariables = VariablesOf; type CsvResult = ResultOf; type UserCsvRow = NonNullable["edges"]>[number]["node"]; const roleNames = (row: UserCsvRow): string => row.userRoles.edges .map((edge) => edge.node.role?.name) .filter((name): name is string => Boolean(name)) .join(", "); const columns: CsvColumn[] = [ { header: "Name", value: (r) => r.name }, { header: "Email", value: (r) => r.email }, { header: "Status", value: (r) => r.status }, { header: "Roles", value: (r) => roleNames(r) }, ]; export function useExportUsersCsv() { 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, UsersCsvQuery, { order, query }, (d) => d.users); if (rows.length === 0) { toast.error("No users to export"); return; } downloadCsv(toCsv(rows, columns), `users-${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 }; }