File size: 6,083 Bytes
fb2a8ad bb909a5 fb2a8ad bb909a5 fb2a8ad | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 | import { authFetch } from "@/lib/api";
import { FilterFormValues } from "@/types/candidate-table";
/**
* Fetch all candidates without pagination for export
*/
export const fetchAllCandidatesForExport = async (
search: string,
sortConfig: { key: string | null; direction: "asc" | "desc" },
filters: FilterFormValues,
criteriaId: string | null
): Promise<any[]> => {
const params = new URLSearchParams()
// Set very high limit to get all results in one request
// Adjust based on your backend's maximum limit
params.set("page", "1")
params.set("limit", "10000") // Fetch up to 10,000 records
if (search) params.set("search", search)
if (sortConfig.key) {
params.set("sortBy", sortConfig.key)
params.set("sortOrder", sortConfig.direction)
}
if (filters.domicile) params.set("domicile", filters.domicile)
if (filters.yoe) params.set("yoe", filters.yoe)
filters.educations.forEach((edu, i) => {
const n = i + 1
if (edu.university) params.set(`univ_edu_${n}`, edu.university)
if (edu.major) params.set(`major_edu_${n}`, edu.major)
if (edu.gpa) params.set(`gpa_${n}`, edu.gpa)
})
if (filters.softskills) params.append("softskills", filters.softskills)
if (filters.hardskills) params.append("hardskills", filters.hardskills)
if (filters.certifications) params.append("certifications", filters.certifications)
if (filters.businessDomain) params.append("business_domain", filters.businessDomain)
if (criteriaId) params.append("criteria_id", criteriaId)
const res = await authFetch(`/api/cv-profile?${params}`)
if (!res.ok) throw new Error("Failed to fetch candidates for export")
const data = await res.json()
return data.data ?? []
}
/**
* Convert candidates array to CSV string
*/
export const generateCSVContent = (candidates: any[]): string => {
if (candidates.length === 0) return ""
// Define all possible columns
const columns = [
"profile_id",
"fullname",
"domicile",
"yoe",
"univ_edu_1",
"major_edu_1",
"gpa_edu_1",
"univ_edu_2",
"major_edu_2",
"gpa_edu_2",
"univ_edu_3",
"major_edu_3",
"gpa_edu_3",
"hardskills",
"softskills",
"certifications",
"business_domain",
"score",
]
// CSV Header
const header = columns.join(",")
// CSV Rows
const rows = candidates.map((candidate) =>
columns
.map((col) => {
const value = candidate[col]
// Handle arrays (join with semicolon)
if (Array.isArray(value)) {
return `"${value.join("; ")}"`
}
// Handle null/undefined
if (value === null || value === undefined) {
return ""
}
// Handle strings with commas or quotes (escape them)
const stringValue = String(value)
if (stringValue.includes(",") || stringValue.includes('"') || stringValue.includes("\n")) {
return `"${stringValue.replace(/"/g, '""')}"` // Escape quotes
}
return stringValue
})
.join(",")
)
return [header, ...rows].join("\n")
}
/**
* Trigger CSV download in browser
*/
export const downloadCSV = (content: string, filename: string = "candidates.csv"): void => {
const blob = new Blob([content], { type: "text/csv;charset=utf-8;" })
const link = document.createElement("a")
const url = URL.createObjectURL(blob)
link.setAttribute("href", url)
link.setAttribute("download", filename)
link.style.visibility = "hidden"
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
URL.revokeObjectURL(url)
}
/**
* Main export function - orchestrates fetch, generate, and download
*/
export const exportCandidatesToCSV = async (
search: string,
sortConfig: { key: string | null; direction: "asc" | "desc" },
filters: FilterFormValues,
criteriaId: string | null,
userId: string
): Promise<void> => {
try {
const params = new URLSearchParams()
if (search) params.set("search", search)
if (sortConfig.key) {
params.set("sortBy", sortConfig.key)
params.set("sortOrder", sortConfig.direction)
}
if (filters.domicile) params.set("domicile", filters.domicile)
if (filters.yoe) params.set("yoe", filters.yoe)
filters.educations.forEach((edu, i) => {
const n = i + 1
// Handle arrays for university and major
edu.university.forEach((univ) => params.append(`univ_edu_${n}`, univ))
edu.major.forEach((maj) => params.append(`major_edu_${n}`, maj))
if (edu.gpa) params.set(`gpa_${n}`, edu.gpa)
})
// Updated to handle arrays
filters.softskills.forEach((skill) => params.append("softskills", skill))
filters.hardskills.forEach((skill) => params.append("hardskills", skill))
filters.certifications.forEach((cert) => params.append("certifications", cert))
filters.businessDomain.forEach((domain) => params.append("business_domain", domain))
if (criteriaId) params.append("criteria_id", criteriaId)
params.append("user_id", userId)
// Call backend export endpoint
const response = await authFetch(`/api/cv-profile/export?${params}`, {
method: "GET",
headers: {
"Accept": "text/csv",
},
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.error || "Export failed")
}
// Get blob and trigger download
const blob = await response.blob()
const url = window.URL.createObjectURL(blob)
const link = document.createElement("a")
link.href = url
// Extract filename from Content-Disposition header
const contentDisposition = response.headers.get("Content-Disposition")
const filename = contentDisposition
? contentDisposition.split("filename=")[1]?.replace(/"/g, "")
: `candidates-${new Date().toISOString().slice(0, 10)}.csv`
link.setAttribute("download", filename)
document.body.appendChild(link)
link.click()
// Cleanup
document.body.removeChild(link)
window.URL.revokeObjectURL(url)
} catch (error) {
console.error("Export failed:", error)
throw error
}
} |