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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
//! The `Excel` facade: `Maatwebsite\Excel\Excel`, with the `Exportable` and `Importable` traits.

use std::fmt;
use std::future::{Future, IntoFuture};
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::sync::{Arc, Mutex};

use laravel::http::{Download, UploadedFile};
use laravel::queue::{BatchId, ChainDispatched};
use serde::{Deserialize, Serialize};

use crate::config::ExcelConfig;
use crate::error::ExcelError;
use crate::events::GlobalListeners;
use crate::export::{Export, ExportContext};
use crate::fake::FakeState;
use crate::import::{Import, ImportContext, SheetRows, SheetWindow};
use crate::reader::{ReadOptions, ReadSheet};
use crate::sheets::SheetKey;

/// A reader or writer type: the `Excel::XLSX`, `Excel::CSV`.. constants.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Type {
    /// `Excel::XLSX`: read and written.
    Xlsx,
    /// `Excel::CSV`: read and written.
    Csv,
    /// `Excel::TSV`: CSV with a tab delimiter.
    Tsv,
    /// `Excel::ODS`: read and written.
    Ods,
    /// `Excel::XLS`: read only.
    Xls,
    /// `Excel::SLK`: read only, as in PhpSpreadsheet.
    Slk,
    /// `Excel::XML` (SpreadsheetML 2003): read only, as in PhpSpreadsheet.
    Xml,
    /// `Excel::GNUMERIC`: read only, as in PhpSpreadsheet.
    Gnumeric,
    /// `Excel::HTML`: read and written.
    Html,
    /// `Excel::MPDF`: written as PDF by laravel-pdf.
    Mpdf,
    /// `Excel::DOMPDF`: written as PDF by laravel-pdf.
    Dompdf,
    /// `Excel::TCPDF`: written as PDF by laravel-pdf.
    Tcpdf,
}

impl fmt::Display for Type {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let name = match self {
            Self::Xlsx => "Xlsx",
            Self::Csv | Self::Tsv => "Csv",
            Self::Ods => "Ods",
            Self::Xls => "Xls",
            Self::Slk => "Slk",
            Self::Xml => "Xml",
            Self::Gnumeric => "Gnumeric",
            Self::Html => "Html",
            Self::Mpdf => "Mpdf",
            Self::Dompdf => "Dompdf",
            Self::Tcpdf => "Tcpdf",
        };
        f.write_str(name)
    }
}

fn extension(path: &str) -> Option<String> {
    Path::new(path)
        .extension()
        .map(|extension| extension.to_string_lossy().to_lowercase())
        .filter(|extension| !extension.trim().is_empty())
}

/// `FileTypeDetector::detect()`: the explicit type, or the type of the file's extension.
pub(crate) fn detect(path: &str, explicit: Option<Type>, config: &ExcelConfig) -> Result<Option<Type>, ExcelError> {
    if explicit.is_some() {
        return Ok(explicit);
    }
    let extension = extension(path).ok_or(ExcelError::NoTypeDetected)?;
    Ok(config.extension_detector.get(&extension).copied())
}

/// `FileTypeDetector::detectStrict()`.
pub(crate) fn detect_strict(path: &str, explicit: Option<Type>, config: &ExcelConfig) -> Result<Type, ExcelError> {
    detect(path, explicit, config)?.ok_or(ExcelError::NoTypeDetected)
}

/// `IOFactory::identify()`: the type of a file from its contents.
fn identify(bytes: &[u8]) -> Type {
    if bytes.starts_with(b"PK") {
        let head = &bytes[..bytes.len().min(200)];
        if head.windows(8).any(|window| window == b"mimetype")
            && head.windows(11).any(|window| window == b"opendocumen")
        {
            return Type::Ods;
        }
        return Type::Xlsx;
    }
    if bytes.starts_with(&[0xD0, 0xCF, 0x11, 0xE0]) {
        return Type::Xls;
    }
    if bytes.starts_with(&[0x1F, 0x8B]) {
        return Type::Gnumeric;
    }
    if bytes.starts_with(b"ID;") {
        return Type::Slk;
    }
    let head = String::from_utf8_lossy(&bytes[..bytes.len().min(2048)]).to_ascii_lowercase();
    if head.contains("urn:schemas-microsoft-com:office:spreadsheet") {
        return Type::Xml;
    }
    if head.trim_start().starts_with("<!doctype html") || head.contains("<html") || head.contains("<table") {
        return Type::Html;
    }
    Type::Csv
}

/// The state behind the facade: the global event listeners and the fake.
#[derive(Clone, Default)]
pub struct ExcelState {
    pub(crate) listeners: GlobalListeners,
    pub(crate) fake: Arc<Mutex<Option<Arc<FakeState>>>>,
}

pub(crate) async fn state() -> ExcelState {
    match laravel::container::resolve::<ExcelState>().await {
        Ok(state) => (*state).clone(),
        Err(_) => ExcelState::default(),
    }
}

pub(crate) async fn global_listeners() -> GlobalListeners {
    state().await.listeners
}

pub(crate) async fn fake() -> Option<Arc<FakeState>> {
    state()
        .await
        .fake
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .clone()
}

/// A file to import: a path on a disk or on the local filesystem, or an uploaded file.
#[derive(Debug, Clone)]
pub enum ImportFile {
    /// A path: on the given disk, or on the local filesystem when it exists there and isn't on
    /// the default disk, else on the default disk, as `TemporaryFile::copyFrom()` decides.
    Path(String),
    /// An uploaded file, read from its temporary path, with the name the client gave it.
    Uploaded {
        /// The temporary file.
        path: PathBuf,
        /// The client's file name, whose extension decides the type.
        name: String,
    },
}

impl ImportFile {
    /// The name that decides the file's type, and the key the fake records it under.
    pub fn name(&self) -> &str {
        match self {
            Self::Path(path) => path,
            Self::Uploaded { name, .. } => name,
        }
    }

    pub(crate) async fn read(&self, disk: Option<&str>) -> laravel::Result<Vec<u8>> {
        match self {
            Self::Uploaded { path, .. } => Ok(std::fs::read(path)?),
            Self::Path(path) => {
                if disk.is_none() {
                    let local = Path::new(path);
                    let absolute = if local.is_absolute() {
                        local.to_path_buf()
                    } else {
                        laravel::config().app.base_path.join(local)
                    };
                    if absolute.is_file() {
                        let on_default_disk = match laravel::storage::default_disk() {
                            Ok(default) if !local.is_absolute() => default.exists(path).await.unwrap_or(false),
                            _ => false,
                        };
                        if !on_default_disk {
                            return Ok(std::fs::read(absolute)?);
                        }
                    }
                }
                let storage = match disk {
                    Some(name) => laravel::storage::disk(name)?,
                    None => laravel::storage::default_disk()?,
                };
                if !storage.exists(path).await? {
                    let mut log = format!("[{path}]");
                    if let Some(disk) = disk {
                        log.push_str(&format!(" ({disk})"));
                    }
                    return Err(ExcelError::UnreadableFile(format!(
                        "File {log} does not exist and can therefore not be imported."
                    ))
                    .into());
                }
                Ok(storage.get_with_limit(path, u64::MAX).await?.to_vec())
            }
        }
    }
}

impl From<&str> for ImportFile {
    fn from(path: &str) -> Self {
        Self::Path(path.to_owned())
    }
}

impl From<String> for ImportFile {
    fn from(path: String) -> Self {
        Self::Path(path)
    }
}

impl From<&String> for ImportFile {
    fn from(path: &String) -> Self {
        Self::Path(path.clone())
    }
}

impl From<&UploadedFile> for ImportFile {
    fn from(file: &UploadedFile) -> Self {
        Self::Uploaded {
            path: file.path().to_path_buf(),
            name: file.client_name().to_owned(),
        }
    }
}

/// What queueing an export or import dispatched.
#[derive(Debug)]
pub enum Queued {
    /// A chain of jobs: `PendingDispatch`.
    Chain(ChainDispatched),
    /// A job batch, for `ShouldBatch`: `PendingBatch`.
    Batch(BatchId),
    /// Separate jobs, for `ShouldQueueWithoutChain`.
    Jobs(usize),
    /// Nothing was dispatched, because `Excel` is faked.
    Faked,
}

type BoxedFuture<'a, T> = Pin<Box<dyn Future<Output = laravel::Result<T>> + Send + 'a>>;

/// Laravel Excel's facade: download, store, queue and import spreadsheets.
///
/// ```ignore
/// use laravel_excel::Excel;
///
/// pub async fn export() -> laravel::Result<Download> {
///     Excel::download(&UsersExport, "users.xlsx").await
/// }
///
/// Excel::store(&InvoicesExport::new(2018), "invoices.xlsx").disk("s3").await?;
/// Excel::import(&UsersImport, "users.xlsx").await?;
/// let rows = Excel::to_array(&UsersImport, "users.xlsx").await?;
/// ```
pub struct Excel;

impl Excel {
    /// `Excel::download()`: the export as a download named `file_name`, in the type of its
    /// extension unless [`writer_type`](PendingDownload::writer_type) says otherwise.
    pub fn download<'a, E: AsDynExport + ?Sized>(
        export: &'a E,
        file_name: impl Into<String>,
    ) -> PendingDownload<'a, E> {
        PendingDownload {
            export,
            file_name: file_name.into(),
            writer_type: None,
            headers: Vec::new(),
        }
    }

    /// `Excel::store()`: writes the export to `file_path` on a disk, or queues it for an export
    /// with `ShouldQueue`. Resolves to `true` once stored or queued.
    pub fn store<'a, E: AsDynExport + ?Sized>(export: &'a E, file_path: impl Into<String>) -> PendingStore<'a, E> {
        PendingStore {
            export,
            file_path: file_path.into(),
            disk: None,
            writer_type: None,
        }
    }

    /// `Excel::queue()`: queues the export to be written to `file_path`. The export must be
    /// declared `Queueable` or `ShouldQueue` in [`export!`](crate::export).
    pub fn queue<'a, E: AsDynExport + ?Sized>(export: &'a E, file_path: impl Into<String>) -> PendingQueue<'a, E> {
        PendingQueue {
            export,
            file_path: file_path.into(),
            disk: None,
            writer_type: None,
        }
    }

    /// `Excel::raw()`: the export's file contents.
    pub async fn raw<E: AsDynExport + ?Sized>(export: &E, writer_type: Type) -> laravel::Result<Vec<u8>> {
        let export = export.__as_dyn();
        if let Some(fake) = fake().await {
            fake.record_raw(export);
            return Ok(b"RAW-CONTENTS".to_vec());
        }
        let context = ExportContext::current().await;
        let mut spreadsheet = crate::export::build(export, &context).await?;
        write_spreadsheet(export, &mut spreadsheet, writer_type, None, &context)
    }

    /// `Excel::import()`: imports a file, from the default disk unless
    /// [`disk`](PendingImport::disk) names another. An import with `ShouldQueue` and
    /// `WithChunkReading` is queued.
    pub fn import<'a, I: AsDynImport + ?Sized>(import: &'a I, file: impl Into<ImportFile>) -> PendingImport<'a, I> {
        PendingImport {
            import,
            file: file.into(),
            disk: None,
            reader_type: None,
        }
    }

    /// `Excel::queueImport()`: queues the import; it needs `ShouldQueue` and `WithChunkReading`.
    pub fn queue_import<'a, I: AsDynImport + ?Sized>(
        import: &'a I,
        file: impl Into<ImportFile>,
    ) -> PendingQueueImport<'a, I> {
        PendingQueueImport(PendingImport {
            import,
            file: file.into(),
            disk: None,
            reader_type: None,
        })
    }

    /// `Excel::toArray()`: the rows of each sheet.
    pub fn to_array<'a, I: AsDynImport + ?Sized>(import: &'a I, file: impl Into<ImportFile>) -> PendingRows<'a, I> {
        PendingRows(PendingImport {
            import,
            file: file.into(),
            disk: None,
            reader_type: None,
        })
    }

    /// `Excel::toCollection()`: the rows of each sheet. In Rust it returns the same as
    /// [`to_array`](Self::to_array).
    pub fn to_collection<'a, I: AsDynImport + ?Sized>(
        import: &'a I,
        file: impl Into<ImportFile>,
    ) -> PendingRows<'a, I> {
        Self::to_array(import, file)
    }
}

/// Lets generic code turn any export or import, sized or `dyn`, into a trait object.
#[doc(hidden)]
pub trait AsDynExport: Sync {
    fn __as_dyn(&self) -> &dyn Export;
}

impl<E: Export> AsDynExport for E {
    fn __as_dyn(&self) -> &dyn Export {
        self
    }
}

impl AsDynExport for dyn Export {
    fn __as_dyn(&self) -> &dyn Export {
        self
    }
}

#[doc(hidden)]
pub trait AsDynImport: Sync {
    fn __as_dyn(&self) -> &dyn Import;
}

impl<I: Import> AsDynImport for I {
    fn __as_dyn(&self) -> &dyn Import {
        self
    }
}

impl AsDynImport for dyn Import {
    fn __as_dyn(&self) -> &dyn Import {
        self
    }
}

/// Writes a built workbook as `writer_type`, raising `BeforeWriting`: `Writer::write()`.
pub(crate) fn write_spreadsheet(
    export: &dyn Export,
    spreadsheet: &mut crate::spreadsheet::Spreadsheet,
    writer_type: Type,
    file_name: Option<&str>,
    context: &ExportContext,
) -> laravel::Result<Vec<u8>> {
    crate::export::before_writing(export, spreadsheet, context)?;
    let concerns = export.__concerns();
    let mut csv = match concerns.csv_settings {
        Some(settings) => settings.csv_settings(),
        None => context.config.exports.csv.clone(),
    };
    let tsv = writer_type == Type::Tsv || file_name.is_some_and(|name| extension(name).as_deref() == Some("tsv"));
    if tsv && concerns.csv_settings.is_none() {
        csv.delimiter = "\t".to_owned();
    }
    let pre_calculate = concerns.pre_calculate_formulas || context.config.exports.pre_calculate_formulas;
    Ok(crate::writer::write(spreadsheet, writer_type, &csv, pre_calculate)?)
}

/// Builds and writes an export.
pub(crate) async fn export_bytes(export: &dyn Export, file_name: &str, writer_type: Type) -> laravel::Result<Vec<u8>> {
    let context = ExportContext::current().await;
    let mut spreadsheet = crate::export::build(export, &context).await?;
    write_spreadsheet(export, &mut spreadsheet, writer_type, Some(file_name), &context)
}

/// A download being prepared: await it for the response.
#[must_use = "await the download to build the response"]
pub struct PendingDownload<'a, E: ?Sized> {
    export: &'a E,
    file_name: String,
    writer_type: Option<Type>,
    headers: Vec<(String, String)>,
}

impl<E: ?Sized> PendingDownload<'_, E> {
    /// Writes this type instead of the file name's.
    pub fn writer_type(mut self, writer_type: Type) -> Self {
        self.writer_type = Some(writer_type);
        self
    }

    /// Adds response headers.
    pub fn headers<K: Into<String>, V: Into<String>>(mut self, headers: impl IntoIterator<Item = (K, V)>) -> Self {
        self.headers
            .extend(headers.into_iter().map(|(name, value)| (name.into(), value.into())));
        self
    }
}

impl<'a, E: AsDynExport + ?Sized> IntoFuture for PendingDownload<'a, E> {
    type Output = laravel::Result<Download>;
    type IntoFuture = BoxedFuture<'a, Download>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move {
            let export = self.export.__as_dyn();
            if let Some(fake) = fake().await {
                fake.record_download(&self.file_name, export);
                return Ok(Download::new(self.file_name, Vec::<u8>::new()));
            }
            let config = crate::config::current();
            let writer_type = detect_strict(&self.file_name, self.writer_type, &config)?;
            let bytes = export_bytes(export, &self.file_name, writer_type).await?;
            let mut download = Download::new(self.file_name, bytes);
            for (name, value) in self.headers {
                download = download.with_header(name, value);
            }
            Ok(download)
        })
    }
}

/// A store being prepared: await it to write the file.
#[must_use = "await the store to write the file"]
pub struct PendingStore<'a, E: ?Sized> {
    export: &'a E,
    file_path: String,
    disk: Option<String>,
    writer_type: Option<Type>,
}

impl<E: ?Sized> PendingStore<'_, E> {
    /// Stores on this disk instead of the default disk.
    pub fn disk(mut self, disk: impl Into<String>) -> Self {
        self.disk = Some(disk.into());
        self
    }

    /// Writes this type instead of the file path's.
    pub fn writer_type(mut self, writer_type: Type) -> Self {
        self.writer_type = Some(writer_type);
        self
    }
}

impl<'a, E: AsDynExport + ?Sized> IntoFuture for PendingStore<'a, E> {
    type Output = laravel::Result<bool>;
    type IntoFuture = BoxedFuture<'a, bool>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move {
            let export = self.export.__as_dyn();
            if export.__concerns().should_queue.is_some() {
                crate::queue::queue_export(export, &self.file_path, self.disk.as_deref(), self.writer_type).await?;
                return Ok(true);
            }
            if let Some(fake) = fake().await {
                fake.record_store(self.disk.as_deref(), &self.file_path, export);
                return Ok(true);
            }
            let config = crate::config::current();
            let writer_type = detect_strict(&self.file_path, self.writer_type, &config)?;
            let bytes = export_bytes(export, &self.file_path, writer_type).await?;
            let disk = match &self.disk {
                Some(name) => laravel::storage::disk(name)?,
                None => laravel::storage::default_disk()?,
            };
            disk.put(&self.file_path, bytes).await?;
            Ok(true)
        })
    }
}

/// A queued export being prepared: await it to dispatch the jobs.
#[must_use = "await the queue to dispatch the jobs"]
pub struct PendingQueue<'a, E: ?Sized> {
    export: &'a E,
    file_path: String,
    disk: Option<String>,
    writer_type: Option<Type>,
}

impl<E: ?Sized> PendingQueue<'_, E> {
    /// Stores on this disk instead of the default disk.
    pub fn disk(mut self, disk: impl Into<String>) -> Self {
        self.disk = Some(disk.into());
        self
    }

    /// Writes this type instead of the file path's.
    pub fn writer_type(mut self, writer_type: Type) -> Self {
        self.writer_type = Some(writer_type);
        self
    }
}

impl<'a, E: AsDynExport + ?Sized> IntoFuture for PendingQueue<'a, E> {
    type Output = laravel::Result<Queued>;
    type IntoFuture = BoxedFuture<'a, Queued>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move {
            crate::queue::queue_export(
                self.export.__as_dyn(),
                &self.file_path,
                self.disk.as_deref(),
                self.writer_type,
            )
            .await
        })
    }
}

/// An import being prepared: await it to import the file.
#[must_use = "await the import to read the file"]
pub struct PendingImport<'a, I: ?Sized> {
    import: &'a I,
    file: ImportFile,
    disk: Option<String>,
    reader_type: Option<Type>,
}

impl<I: ?Sized> PendingImport<'_, I> {
    /// Reads the file from this disk.
    pub fn disk(mut self, disk: impl Into<String>) -> Self {
        self.disk = Some(disk.into());
        self
    }

    /// Reads this type instead of the file name's.
    pub fn reader_type(mut self, reader_type: Type) -> Self {
        self.reader_type = Some(reader_type);
        self
    }
}

impl<'a, I: AsDynImport + ?Sized> IntoFuture for PendingImport<'a, I> {
    type Output = laravel::Result<Option<Queued>>;
    type IntoFuture = BoxedFuture<'a, Option<Queued>>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move {
            let import = self.import.__as_dyn();
            if let Some(fake) = fake().await {
                if import.__concerns().should_queue.is_some() {
                    fake.record_queued_import(self.disk.as_deref(), self.file.name(), import);
                    return Ok(Some(Queued::Faked));
                }
                fake.record_import(self.disk.as_deref(), self.file.name(), import);
                return Ok(None);
            }
            read(import, &self.file, self.disk.as_deref(), self.reader_type).await
        })
    }
}

/// A queued import being prepared.
#[must_use = "await the import to dispatch its jobs"]
pub struct PendingQueueImport<'a, I: ?Sized>(PendingImport<'a, I>);

impl<I: ?Sized> PendingQueueImport<'_, I> {
    /// Reads the file from this disk.
    pub fn disk(self, disk: impl Into<String>) -> Self {
        Self(self.0.disk(disk))
    }

    /// Reads this type instead of the file name's.
    pub fn reader_type(self, reader_type: Type) -> Self {
        Self(self.0.reader_type(reader_type))
    }
}

impl<'a, I: AsDynImport + ?Sized> IntoFuture for PendingQueueImport<'a, I> {
    type Output = laravel::Result<Queued>;
    type IntoFuture = BoxedFuture<'a, Queued>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move {
            if self.0.import.__as_dyn().__concerns().should_queue.is_none() {
                return Err(ExcelError::NotQueueable.into());
            }
            self.0.await?.ok_or_else(|| ExcelError::NotQueueable.into())
        })
    }
}

/// Rows being read: await them for each sheet's rows.
#[must_use = "await the rows to read the file"]
pub struct PendingRows<'a, I: ?Sized>(PendingImport<'a, I>);

impl<I: ?Sized> PendingRows<'_, I> {
    /// Reads the file from this disk.
    pub fn disk(self, disk: impl Into<String>) -> Self {
        Self(self.0.disk(disk))
    }

    /// Reads this type instead of the file name's.
    pub fn reader_type(self, reader_type: Type) -> Self {
        Self(self.0.reader_type(reader_type))
    }
}

impl<'a, I: AsDynImport + ?Sized> IntoFuture for PendingRows<'a, I> {
    type Output = laravel::Result<SheetRows>;
    type IntoFuture = BoxedFuture<'a, SheetRows>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move {
            let pending = self.0;
            let import = pending.import.__as_dyn();
            if let Some(fake) = fake().await {
                fake.record_import(pending.disk.as_deref(), pending.file.name(), import);
                return Ok(SheetRows::new());
            }
            to_rows(import, &pending.file, pending.disk.as_deref(), pending.reader_type).await
        })
    }
}

/// Reads a file into sheets.
pub(crate) async fn load(
    import: &dyn Import,
    bytes: &[u8],
    file_name: &str,
    reader_type: Option<Type>,
    config: &ExcelConfig,
) -> laravel::Result<(Type, Vec<ReadSheet>)> {
    let kind = match detect(file_name, reader_type, config)? {
        Some(kind) => kind,
        None => identify(bytes),
    };
    let concerns = import.__concerns();
    let csv = match concerns.csv_settings {
        Some(settings) => settings.csv_import_settings(),
        None => config.imports.csv.clone(),
    };
    let options = ReadOptions {
        csv,
        ignore_empty: config.imports.ignore_empty,
        binder: concerns.binder(config),
        tsv: extension(file_name).as_deref() == Some("tsv"),
        style_information: crate::import::requires_style_information(import),
    };
    let mut sheets = crate::reader::read(bytes, kind, &options)?;
    if let Some(filter) = concerns.read_filter {
        for sheet in &mut sheets {
            sheet.filter(filter);
        }
    }
    Ok((kind, sheets))
}

/// `Reader::read()`.
async fn read(
    import: &dyn Import,
    file: &ImportFile,
    disk: Option<&str>,
    reader_type: Option<Type>,
) -> laravel::Result<Option<Queued>> {
    let concerns = import.__concerns();
    let queued = concerns.should_queue.is_some();
    let chunked = concerns.chunk_reading.is_some();
    drop(concerns);
    if queued && !chunked {
        return Err(ExcelError::QueueWithoutChunkReading.into());
    }
    let context = ImportContext::current().await;
    let bytes = file.read(disk).await?;
    if chunked {
        return crate::queue::read_in_chunks(import, bytes, file.name(), reader_type, &context).await;
    }

    let result: laravel::Result<()> = async {
        let (_, mut sheets) = load(import, &bytes, file.name(), reader_type, &context.config).await?;
        let owned = match import.__concerns().multiple_sheets {
            Some(multiple) => multiple.sheets().imports(),
            None => Vec::new(),
        };
        let pairs: Vec<(SheetKey, usize, &dyn Import)> = crate::import::sheet_imports(import, &sheets, &owned)?
            .into_iter()
            .collect();
        let total_rows = crate::import::total_rows(&sheets);
        crate::import::before_import(import, &total_rows, &context.listeners)?;
        crate::import::transaction(&context.config, async || {
            for (_, index, sheet_import) in &pairs {
                let start_row = sheet_import.__concerns().start_row_number();
                let window = SheetWindow {
                    start_row,
                    end_row: None,
                    chunk_offset: None,
                };
                crate::import::import_sheet(*sheet_import, &mut sheets[*index], window, &context).await?;
            }
            Ok(())
        })
        .await?;
        crate::import::after_import(import, &total_rows, &context.listeners)
    }
    .await;
    if let Err(error) = &result {
        crate::import::import_failed(import, error, &context.listeners);
    }
    result.map(|()| None)
}

/// `Reader::toArray()`.
async fn to_rows(
    import: &dyn Import,
    file: &ImportFile,
    disk: Option<&str>,
    reader_type: Option<Type>,
) -> laravel::Result<SheetRows> {
    let context = ImportContext::current().await;
    let bytes = file.read(disk).await?;
    let (_, sheets) = load(import, &bytes, file.name(), reader_type, &context.config).await?;
    let owned = match import.__concerns().multiple_sheets {
        Some(multiple) => multiple.sheets().imports(),
        None => Vec::new(),
    };
    let pairs = crate::import::sheet_imports(import, &sheets, &owned)?;
    let total_rows = crate::import::total_rows(&sheets);
    crate::import::before_import(import, &total_rows, &context.listeners)?;
    let mut result = SheetRows::new();
    for (key, index, sheet_import) in pairs {
        let start_row = sheet_import.__concerns().start_row_number();
        let middleware = context.config.imports.cell_middleware.clone();
        let sheet = crate::import::SheetImport {
            sheet: &sheets[index],
            start_row,
            end_row: None,
            chunk_offset: None,
            middleware: &middleware,
            listeners: &context.listeners,
            ignore_empty: context.config.imports.ignore_empty,
        };
        let rows = crate::import::to_rows(&sheet, sheet_import).await?;
        result.insert(key, rows);
    }
    crate::import::after_import(import, &total_rows, &context.listeners)?;
    Ok(result)
}

// ---------------------------------------------------------------------------------------------
// Exportable and Importable
// ---------------------------------------------------------------------------------------------

/// `Exportable`: lets an export download, store, queue and write itself, with defaults for the
/// file name, path, disk and type, like the trait's `$fileName`, `$filePath`.. properties.
pub trait Exportable: Export + Sized {
    /// `$fileName`: the download's default name.
    fn file_name(&self) -> Option<String> {
        None
    }

    /// `$writerType`: the default type.
    fn writer_type(&self) -> Option<Type> {
        None
    }

    /// `$headers`: the download's default headers.
    fn headers(&self) -> Vec<(String, String)> {
        Vec::new()
    }

    /// `$filePath`: the default path to store at.
    fn file_path(&self) -> Option<String> {
        None
    }

    /// `$disk`: the default disk.
    fn disk(&self) -> Option<String> {
        None
    }

    /// `download()`: downloads as `file_name`, or the default file name.
    fn download(&self, file_name: Option<&str>) -> impl Future<Output = laravel::Result<Download>> + Send {
        async move {
            let file_name = file_name
                .map(str::to_owned)
                .or_else(|| self.file_name())
                .ok_or(ExcelError::NoFilenameGiven)?;
            let mut pending = Excel::download(self, file_name).headers(self.headers());
            if let Some(writer_type) = self.writer_type() {
                pending = pending.writer_type(writer_type);
            }
            pending.await
        }
    }

    /// `store()`: stores at `file_path`, or the default path, on the default disk of the export.
    fn store(&self, file_path: Option<&str>) -> impl Future<Output = laravel::Result<bool>> + Send {
        async move {
            let file_path = file_path
                .map(str::to_owned)
                .or_else(|| self.file_path())
                .ok_or(ExcelError::NoExportFilePathGiven)?;
            let mut pending = Excel::store(self, file_path);
            if let Some(disk) = self.disk() {
                pending = pending.disk(disk);
            }
            if let Some(writer_type) = self.writer_type() {
                pending = pending.writer_type(writer_type);
            }
            pending.await
        }
    }

    /// `queue()`: queues the export to `file_path`, or the default path.
    fn queue(&self, file_path: Option<&str>) -> impl Future<Output = laravel::Result<Queued>> + Send {
        async move {
            let file_path = file_path
                .map(str::to_owned)
                .or_else(|| self.file_path())
                .ok_or(ExcelError::NoExportFilePathGiven)?;
            let mut pending = Excel::queue(self, file_path);
            if let Some(disk) = self.disk() {
                pending = pending.disk(disk);
            }
            if let Some(writer_type) = self.writer_type() {
                pending = pending.writer_type(writer_type);
            }
            pending.await
        }
    }

    /// `raw()`: the file's contents as `writer_type`, or the default type.
    fn raw(&self, writer_type: Option<Type>) -> impl Future<Output = laravel::Result<Vec<u8>>> + Send {
        async move {
            let writer_type = writer_type
                .or_else(|| self.writer_type())
                .ok_or(ExcelError::NoTypeDetected)?;
            Excel::raw(self, writer_type).await
        }
    }
}

/// `Importable`: lets an import read a file itself, with defaults for the file path, disk and
/// type, like the trait's `$filePath`, `$disk` and `$readerType` properties.
pub trait Importable: Import + Sized {
    /// `$filePath`: the default file.
    fn file_path(&self) -> Option<String> {
        None
    }

    /// `$disk`: the default disk.
    fn disk(&self) -> Option<String> {
        None
    }

    /// `$readerType`: the default type.
    fn reader_type(&self) -> Option<Type> {
        None
    }

    /// `import()`: imports `file`, or the default file.
    fn import(&self, file: Option<ImportFile>) -> impl Future<Output = laravel::Result<Option<Queued>>> + Send {
        async move {
            let file = file
                .or_else(|| self.file_path().map(ImportFile::Path))
                .ok_or(ExcelError::NoImportFilePathGiven)?;
            let mut pending = Excel::import(self, file);
            if let Some(disk) = self.disk() {
                pending = pending.disk(disk);
            }
            if let Some(reader_type) = self.reader_type() {
                pending = pending.reader_type(reader_type);
            }
            pending.await
        }
    }

    /// `toArray()`: the rows of each sheet of `file`, or the default file.
    fn to_array(&self, file: Option<ImportFile>) -> impl Future<Output = laravel::Result<SheetRows>> + Send {
        async move {
            let file = file
                .or_else(|| self.file_path().map(ImportFile::Path))
                .ok_or(ExcelError::NoImportFilePathGiven)?;
            let mut pending = Excel::to_array(self, file);
            if let Some(disk) = self.disk() {
                pending = pending.disk(disk);
            }
            if let Some(reader_type) = self.reader_type() {
                pending = pending.reader_type(reader_type);
            }
            pending.await
        }
    }

    /// `toCollection()`: the same as [`to_array`](Self::to_array).
    fn to_collection(&self, file: Option<ImportFile>) -> impl Future<Output = laravel::Result<SheetRows>> + Send {
        self.to_array(file)
    }

    /// `queue()`: queues the import; it needs `ShouldQueue`.
    fn queue(&self, file: Option<ImportFile>) -> impl Future<Output = laravel::Result<Queued>> + Send {
        async move {
            let file = file
                .or_else(|| self.file_path().map(ImportFile::Path))
                .ok_or(ExcelError::NoImportFilePathGiven)?;
            let mut pending = Excel::queue_import(self, file);
            if let Some(disk) = self.disk() {
                pending = pending.disk(disk);
            }
            if let Some(reader_type) = self.reader_type() {
                pending = pending.reader_type(reader_type);
            }
            pending.await
        }
    }
}