laravel-excel 0.3.0

Excel, CSV, ODS, HTML and PDF exports and imports with typed columns for Laravel Rust: a port of Laravel Excel (maatwebsite/excel).
Documentation
//! Laravel Excel's errors: the exceptions in `Maatwebsite\Excel\Exceptions` and
//! `Maatwebsite\Excel\Validators\ValidationException`.

use serde::Serialize;

use crate::row::Row;

/// An error of Laravel Excel itself. Each variant is one of Laravel Excel's exceptions, with the
/// same message.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ExcelError {
    /// `NoTypeDetectedException`.
    #[error(
        "No ReaderType or WriterType could be detected. Make sure you either pass a valid extension to the filename or pass an explicit type."
    )]
    NoTypeDetected,
    /// `NoFilenameGivenException`.
    #[error("A filename needs to be passed in order to download the export")]
    NoFilenameGiven,
    /// `NoFilePathGivenException::import()`.
    #[error("A filepath or UploadedFile needs to be passed to start the import.")]
    NoImportFilePathGiven,
    /// `NoFilePathGivenException::export()`.
    #[error("A filepath needs to be passed in order to store the export.")]
    NoExportFilePathGiven,
    /// `SheetNotFoundException::byName()`.
    #[error("Your requested sheet name [{0}] is out of bounds.")]
    SheetNotFoundByName(String),
    /// `SheetNotFoundException::byIndex()`.
    #[error("Your requested sheet index: {index} is out of bounds. The actual number of sheets is {count}.")]
    SheetNotFoundByIndex {
        /// The requested index.
        index: usize,
        /// The number of sheets in the file.
        count: usize,
    },
    /// `ConcernConflictException::queryOrCollectionAndView()`.
    #[error("Cannot use FromQuery, FromScout, FromArray or FromCollection and FromView on the same sheet.")]
    QueryOrCollectionAndView,
    /// `NoSheetsFoundException` from a queued export.
    #[error(
        "Your export did not return any sheet export instances, please make sure your sheets() method always at least returns one instance."
    )]
    NoSheetsFound,
    /// `UnreadableFileException`.
    #[error("{0}")]
    UnreadableFile(String),
    /// `ColumnCollisionException::atLetter()`.
    #[error(
        "Multiple columns were placed on column {0}. Give each column its own letter, or combine them with Column::multiple()."
    )]
    ColumnCollision(String),
    /// `ConcernConflictException::columnsAndHeadings()`.
    #[error(
        "Cannot use WithColumns and WithHeadings on the same sheet. The columns already define the heading row; use the column title instead: Text::make(\"Full Name\")."
    )]
    ColumnsAndHeadings,
    /// `ConcernConflictException::columnsAndMapping()`.
    #[error(
        "Cannot use WithColumns and WithMapping on the same export. The columns already map each value; pass a callback instead: Text::make(\"Name\").value(|row| ...)."
    )]
    ColumnsAndMapping,
    /// `ConcernConflictException::columnsAndMappedCells()`.
    #[error(
        "Cannot use WithColumns and WithMappedCells on the same sheet. WithMappedCells reads scattered coordinates, while columns read a range of rows."
    )]
    ColumnsAndMappedCells,
    /// `ConcernConflictException::columnsAndColumnLimit()`.
    #[error(
        "Cannot use WithColumns and WithColumnLimit on the same sheet. The columns already determine which range is read."
    )]
    ColumnsAndColumnLimit,
    /// `ConcernConflictException::columnsAndGroupedHeadingRow()`.
    #[error(
        "Cannot use WithColumns and WithGroupedHeadingRow on the same sheet. Grouping collects several cells under one heading, which a column cannot represent; use Column::multiple() to read several values from a single cell."
    )]
    ColumnsAndGroupedHeadingRow,
    /// `UnsupportedColumnException::multipleOnExport()`.
    #[error(
        "Column::multiple() reads several values from a single cell and can only be used on an import. Give each value its own column to export them."
    )]
    MultipleColumnsOnExport,
    /// The `InvalidArgumentException` a queued import without `WithChunkReading` throws.
    #[error("ShouldQueue is only supported in combination with WithChunkReading.")]
    QueueWithoutChunkReading,
    /// The `InvalidArgumentException` that `Importable::queue()` throws without `ShouldQueue`.
    #[error("Importable should implement ShouldQueue to be queued.")]
    NotQueueable,
    /// The `InvalidArgumentException` for an unknown heading row formatter.
    #[error("Formatter \"{0}\" does not exist")]
    UnknownFormatter(String),
    /// A writer or reader type this port can't handle, such as `Xls` for writing or `Pdf`.
    #[error("The {0} format isn't supported for {1} by laravel-excel.")]
    UnsupportedType(String, &'static str),
    /// A coordinate or range that doesn't parse, such as `1A`.
    #[error("Invalid cell coordinate [{0}].")]
    InvalidCoordinate(String),
    /// Writing the file failed.
    #[error("Could not write the spreadsheet: {0}")]
    Write(String),
    /// `make:export` or `make:import` can't write the file, such as when it exists.
    #[error("{0}")]
    Command(String),
    /// A queued export or import names a type that `export!` or `import!` didn't register with
    /// `ShouldQueue`.
    #[error("The queued {kind} [{name}] isn't registered: declare it with `ShouldQueue` in `laravel_excel::{kind}!`.")]
    NotRegistered {
        /// `export` or `import`.
        kind: &'static str,
        /// The type's name.
        name: String,
    },
}

/// A row that failed validation: `Maatwebsite\Excel\Validators\Failure`.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Failure {
    row: u32,
    attribute: String,
    errors: Vec<String>,
    values: Row,
}

impl Failure {
    /// Creates a failure for `attribute` on the sheet row `row`.
    pub fn new(row: u32, attribute: impl Into<String>, errors: Vec<String>, values: Row) -> Self {
        Self {
            row,
            attribute: attribute.into(),
            errors,
            values,
        }
    }

    /// The row number in the sheet.
    pub fn row(&self) -> u32 {
        self.row
    }

    /// The heading (or column index) that failed.
    pub fn attribute(&self) -> &str {
        &self.attribute
    }

    /// The validation messages.
    pub fn errors(&self) -> &[String] {
        &self.errors
    }

    /// The row's values.
    pub fn values(&self) -> &Row {
        &self.values
    }

    /// The messages as "There was an error on row :row. :message", like `Failure::toArray()`.
    pub fn to_messages(&self) -> Vec<String> {
        self.errors
            .iter()
            .map(|message| format!("There was an error on row {}. {message}", self.row))
            .collect()
    }
}

/// The rows of an import that failed validation: `Maatwebsite\Excel\Validators\ValidationException`.
///
/// It answers with a `422` like Laravel's `ValidationException`.
#[derive(Debug, Clone, thiserror::Error, laravel::errors::Status)]
#[error("{}", self.message())]
#[status(422)]
pub struct ValidationException {
    failures: Vec<Failure>,
}

impl ValidationException {
    /// Creates the exception from its failures.
    pub fn new(failures: Vec<Failure>) -> Self {
        Self { failures }
    }

    /// The failures, one per attribute of each failed row.
    pub fn failures(&self) -> &[Failure] {
        &self.failures
    }

    /// The messages of each failure, like `ValidationException::errors()`.
    pub fn errors(&self) -> Vec<Vec<String>> {
        self.failures.iter().map(Failure::to_messages).collect()
    }

    fn message(&self) -> String {
        let first = self
            .failures
            .first()
            .and_then(|failure| failure.errors.first())
            .cloned()
            .unwrap_or_else(|| "The given data was invalid.".to_owned());
        match self.failures.len() {
            0 | 1 => first,
            count => format!("{first} (and {} more errors)", count - 1),
        }
    }
}