Skip to main content

ferrox_reports/
lib.rs

1use rust_xlsxwriter::Workbook;
2use serde::Serialize;
3use ferrox_errors::AppError;
4
5pub struct ReportGenerator;
6
7impl ReportGenerator {
8    /// Generates a CSV from a list of serializable items and returns the bytes
9    pub fn to_csv<T: Serialize>(items: &[T]) -> Result<Vec<u8>, AppError> {
10        let mut wtr = csv::Writer::from_writer(vec![]);
11        for item in items {
12            wtr.serialize(item).map_err(|e| AppError::InternalServerError(Box::new(e)))?;
13        }
14        let data = wtr.into_inner().map_err(|e| AppError::InternalServerError(Box::new(e)))?;
15        Ok(data)
16    }
17
18    /// Generates a basic Excel (XLSX) file from raw string data for demonstration
19    /// (In a real app, you would pass columns and rows generically)
20    pub fn to_excel(headers: &[&str], rows: &[Vec<String>]) -> Result<Vec<u8>, AppError> {
21        let mut workbook = Workbook::new();
22        let worksheet = workbook.add_worksheet();
23
24        // Write headers
25        for (col, header) in headers.iter().enumerate() {
26            worksheet.write_string(0, col as u16, *header)
27                .map_err(|e| AppError::InternalServerError(Box::new(e)))?;
28        }
29
30        // Write rows
31        for (row_idx, row) in rows.iter().enumerate() {
32            for (col_idx, cell) in row.iter().enumerate() {
33                worksheet.write_string((row_idx + 1) as u32, col_idx as u16, cell)
34                    .map_err(|e| AppError::InternalServerError(Box::new(e)))?;
35            }
36        }
37
38        let buffer = workbook.save_to_buffer()
39            .map_err(|e| AppError::InternalServerError(Box::new(e)))?;
40            
41        Ok(buffer)
42    }
43}