use serde::Serialize;
use crate::row::Row;
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ExcelError {
#[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,
#[error("A filename needs to be passed in order to download the export")]
NoFilenameGiven,
#[error("A filepath or UploadedFile needs to be passed to start the import.")]
NoImportFilePathGiven,
#[error("A filepath needs to be passed in order to store the export.")]
NoExportFilePathGiven,
#[error("Your requested sheet name [{0}] is out of bounds.")]
SheetNotFoundByName(String),
#[error("Your requested sheet index: {index} is out of bounds. The actual number of sheets is {count}.")]
SheetNotFoundByIndex {
index: usize,
count: usize,
},
#[error("Cannot use FromQuery, FromScout, FromArray or FromCollection and FromView on the same sheet.")]
QueryOrCollectionAndView,
#[error(
"Your export did not return any sheet export instances, please make sure your sheets() method always at least returns one instance."
)]
NoSheetsFound,
#[error("{0}")]
UnreadableFile(String),
#[error(
"Multiple columns were placed on column {0}. Give each column its own letter, or combine them with Column::multiple()."
)]
ColumnCollision(String),
#[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,
#[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,
#[error(
"Cannot use WithColumns and WithMappedCells on the same sheet. WithMappedCells reads scattered coordinates, while columns read a range of rows."
)]
ColumnsAndMappedCells,
#[error(
"Cannot use WithColumns and WithColumnLimit on the same sheet. The columns already determine which range is read."
)]
ColumnsAndColumnLimit,
#[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,
#[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,
#[error("ShouldQueue is only supported in combination with WithChunkReading.")]
QueueWithoutChunkReading,
#[error("Importable should implement ShouldQueue to be queued.")]
NotQueueable,
#[error("Formatter \"{0}\" does not exist")]
UnknownFormatter(String),
#[error("The {0} format isn't supported for {1} by laravel-excel.")]
UnsupportedType(String, &'static str),
#[error("Invalid cell coordinate [{0}].")]
InvalidCoordinate(String),
#[error("Could not write the spreadsheet: {0}")]
Write(String),
#[error("{0}")]
Command(String),
#[error("The queued {kind} [{name}] isn't registered: declare it with `ShouldQueue` in `laravel_excel::{kind}!`.")]
NotRegistered {
kind: &'static str,
name: String,
},
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Failure {
row: u32,
attribute: String,
errors: Vec<String>,
values: Row,
}
impl Failure {
pub fn new(row: u32, attribute: impl Into<String>, errors: Vec<String>, values: Row) -> Self {
Self {
row,
attribute: attribute.into(),
errors,
values,
}
}
pub fn row(&self) -> u32 {
self.row
}
pub fn attribute(&self) -> &str {
&self.attribute
}
pub fn errors(&self) -> &[String] {
&self.errors
}
pub fn values(&self) -> &Row {
&self.values
}
pub fn to_messages(&self) -> Vec<String> {
self.errors
.iter()
.map(|message| format!("There was an error on row {}. {message}", self.row))
.collect()
}
}
#[derive(Debug, Clone, thiserror::Error, laravel::errors::Status)]
#[error("{}", self.message())]
#[status(422)]
pub struct ValidationException {
failures: Vec<Failure>,
}
impl ValidationException {
pub fn new(failures: Vec<Failure>) -> Self {
Self { failures }
}
pub fn failures(&self) -> &[Failure] {
&self.failures
}
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),
}
}
}