|
import { resolve } from 'path'; |
|
import { readdirSync, readFileSync } from 'fs'; |
|
import ExcelJS from 'exceljs'; |
|
import { format } from 'date-fns'; |
|
|
|
async function combineJSONToExcel() { |
|
const logsDirectory = resolve("/logs"); |
|
const jsonFiles = readdirSync(logsDirectory).filter((file) => file.endsWith(".json")); |
|
if (jsonFiles.length === 0) { |
|
console.log("No JSON files found."); |
|
return; |
|
} |
|
const workbook = new ExcelJS.Workbook(); |
|
const worksheet = workbook.addWorksheet("Combined Data"); |
|
worksheet.addRow(["Prompt", "Template", "Search Results", "LLM Response", "User Score", "User Comment", "Timestamp"]); |
|
for (const jsonFile of jsonFiles) { |
|
const filePath = resolve(logsDirectory, jsonFile); |
|
const jsonContent = readFileSync(filePath, "utf-8"); |
|
const jsonData = JSON.parse(jsonContent); |
|
worksheet.addRow([ |
|
jsonData.prompt, |
|
jsonData.template, |
|
jsonData.search_results, |
|
jsonData.llm_response, |
|
jsonData.user_score, |
|
jsonData.user_comment, |
|
jsonFile.replace(".json", "") |
|
]); |
|
} |
|
const buffer = await workbook.xlsx.writeBuffer(); |
|
return buffer; |
|
} |
|
const GET = async ({ locals, request }) => { |
|
try { |
|
const excelBuffer = await combineJSONToExcel(); |
|
const currentDate = new Date(); |
|
const formattedDate = format(currentDate, "yyyy-MM-dd"); |
|
const filename = `user-responses-${formattedDate}.xlsx`; |
|
return new Response(excelBuffer, { |
|
headers: { |
|
"Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", |
|
"Content-Disposition": "attachment; filename=" + filename |
|
} |
|
}); |
|
} catch (e) { |
|
return new Response( |
|
JSON.stringify({ success: false, error: e.message }), |
|
{ |
|
headers: { "Content-Type": "application/json" } |
|
} |
|
); |
|
} |
|
}; |
|
|
|
export { GET }; |
|
|
|
|