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 Roles dashboard (issue #605). */ const RolesCsvQuery = graphql(` query RolesCsv($first: Int, $after: String, $order: [RoleOrderInput], $query: RoleQueryInput) { roles(first: $first, after: $after, order: $order, query: $query) { pageInfo { hasNextPage endCursor } edges { node { name description status permissions } } } } `); type CsvVariables = VariablesOf; type CsvResult = ResultOf; type RoleCsvRow = NonNullable["edges"]>[number]["node"]; const columns: CsvColumn[] = [ { header: "Name", value: (r) => r.name }, { header: "Description", value: (r) => r.description }, { header: "Status", value: (r) => r.status }, // Dashboard shows a "N scopes" count badge; the CSV carries the full scope // list (semicolon-separated) since that's the useful tabular data to filter on. { header: "Permissions", value: (r) => (r.permissions ?? []).join("; ") }, ]; export function useExportRolesCsv() { 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, RolesCsvQuery, { order, query }, (d) => d.roles); if (rows.length === 0) { toast.error("No roles to export"); return; } downloadCsv(toCsv(rows, columns), `roles-${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 }; }