Skip to main content

ferrox_reports/
lib.rs

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