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
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
//! Imports: the `Import` interface, and Laravel Excel's `Reader`, `Sheet` (while importing),
//! `ModelImporter`, `ModelManager` and `RowValidator`.

use std::collections::{BTreeMap, HashMap};
use std::panic::Location;
use std::sync::{Arc, OnceLock, RwLock};

use futures_util::future::BoxFuture;
use indexmap::IndexMap;
use laravel::model::{Columns, IntoRow, Model};
use laravel::validation::ValidationError;

use crate::concerns::{
    OnEachRow, ShouldQueue, ShouldQueueWithoutChain, SkipsEmptyRows, SkipsOnError, SkipsOnFailure, SkipsUnknownSheets,
    ToArray, ToCollection, ToModel, WithBatchInserts, WithChunkReading, WithColumnLimit, WithCustomCsvSettings,
    WithEvents, WithHeadingRow, WithLimit, WithMappedCells, WithMultipleSheets, WithStartRow, WithUpsertColumns,
    WithUpserts, WithValidation,
};
use crate::config::{CellMiddleware, ExcelConfig, ValueBinderKind};
use crate::coordinate::{Coordinate, column_index_from_string};
use crate::error::{ExcelError, Failure, ValidationException};
use crate::events::{AfterBatch, AfterChunk, AfterImport, AfterSheet, BeforeImport, BeforeSheet, GlobalListeners};
use crate::reader::ReadSheet;
use crate::row::{Key, Row};
use crate::sheets::SheetKey;
use crate::value::{DefaultValueBinder, StringValueBinder, Value, ValueBinder};

/// An import: `Maatwebsite\Excel\Concerns\Import`.
///
/// Don't implement it yourself: implement the concerns and declare them with
/// [`import!`](crate::import), which implements this trait.
pub trait Import: Send + Sync {
    #[doc(hidden)]
    fn __concerns(&self) -> ImportConcerns<'_>;

    #[doc(hidden)]
    fn __handle<'a>(&'a self, sheet: &'a SheetImport<'a>) -> BoxFuture<'a, laravel::Result<()>>;

    #[doc(hidden)]
    fn __queue_payload(&self) -> Option<laravel::Result<(&'static str, serde_json::Value)>> {
        None
    }
    #[doc(hidden)]
    fn __type_name(&self) -> &'static str;

    #[doc(hidden)]
    fn __snapshot(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
        None
    }
}

type Mapping<'a> = Box<dyn Fn(Row) -> laravel::Result<Row> + Send + Sync + 'a>;

/// The concerns an import declares.
#[doc(hidden)]
#[derive(Default)]
pub struct ImportConcerns<'a> {
    pub heading_row: Option<&'a (dyn WithHeadingRow + Sync)>,
    pub grouped_heading_row: bool,
    pub start_row: Option<&'a (dyn WithStartRow + Sync)>,
    pub limit: Option<&'a (dyn WithLimit + Sync)>,
    pub column_limit: Option<&'a (dyn WithColumnLimit + Sync)>,
    pub mapped_cells: Option<&'a (dyn WithMappedCells + Sync)>,
    pub mapping: Option<Mapping<'a>>,
    pub validation: Option<&'a (dyn WithValidation + Sync)>,
    pub skips_on_failure: Option<&'a (dyn SkipsOnFailure + Sync)>,
    pub skips_on_error: Option<&'a (dyn SkipsOnError + Sync)>,
    pub skips_empty_rows: Option<&'a (dyn SkipsEmptyRows + Sync)>,
    pub skips_unknown_sheets: Option<&'a (dyn SkipsUnknownSheets + Sync)>,
    pub calculated_formulas: bool,
    pub events: Option<&'a (dyn WithEvents + Sync)>,
    pub csv_settings: Option<&'a (dyn WithCustomCsvSettings + Sync)>,
    pub value_binder: Option<&'a (dyn ValueBinder + Sync)>,
    pub multiple_sheets: Option<&'a (dyn WithMultipleSheets + Sync)>,
    pub batch_inserts: Option<&'a (dyn WithBatchInserts + Sync)>,
    pub chunk_reading: Option<&'a (dyn WithChunkReading + Sync)>,
    pub upserts: Option<&'a (dyn WithUpserts + Sync)>,
    pub upsert_columns: Option<&'a (dyn WithUpsertColumns + Sync)>,
    pub should_queue: Option<&'a (dyn ShouldQueue + Sync)>,
    pub should_batch: bool,
    pub without_chain: Option<&'a (dyn ShouldQueueWithoutChain + Sync)>,
    pub columns: Option<&'a (dyn crate::concerns::WithColumns + Sync)>,
    pub format_data: bool,
    pub strict_null_comparison: bool,
    pub skip_duplicates: bool,
    pub read_filter: Option<&'a (dyn crate::concerns::WithReadFilter + Sync)>,
    pub progress_bar: Option<&'a (dyn crate::concerns::WithProgressBar + Sync)>,
}

impl ImportConcerns<'_> {
    /// `HeadingRowExtractor::headingRow()`.
    fn heading_row_number(&self) -> u32 {
        self.heading_row.map_or(1, |heading| heading.heading_row())
    }

    /// `HeadingRowExtractor::determineStartRow()`.
    pub(crate) fn start_row_number(&self) -> u32 {
        if let Some(start) = self.start_row {
            return start.start_row();
        }
        if self.heading_row.is_some() {
            self.heading_row_number() + 1
        } else {
            1
        }
    }

    /// `EndRowFinder::find()`.
    pub(crate) fn end_row(&self, start_row: u32, highest_row: u32) -> Option<u32> {
        let limit = self.limit?;
        let end = (start_row.max(1) - 1) + limit.limit();
        if end > highest_row { None } else { Some(end) }
    }

    fn end_column(&self) -> laravel::Result<Option<u32>> {
        self.column_limit
            .map(|limit| column_index_from_string(&limit.end_column()))
            .transpose()
            .map_err(Into::into)
    }

    pub(crate) fn binder(&self, config: &ExcelConfig) -> &(dyn ValueBinder + Sync) {
        match (self.value_binder, config.value_binder) {
            (Some(binder), _) => binder,
            (None, ValueBinderKind::Default) => &DefaultValueBinder,
            (None, ValueBinderKind::String) => &StringValueBinder,
            (None, ValueBinderKind::Advanced) => &crate::value::AdvancedValueBinder,
        }
    }
}

// ---------------------------------------------------------------------------------------------
// Heading row formatter
// ---------------------------------------------------------------------------------------------

type Formatter = Arc<dyn Fn(&Value, usize) -> Key + Send + Sync>;

/// The default formatter's name, and the registered formatters.
type Formatters = RwLock<(Option<String>, HashMap<String, Formatter>)>;

fn formatters() -> &'static Formatters {
    static FORMATTERS: OnceLock<Formatters> = OnceLock::new();
    FORMATTERS.get_or_init(|| RwLock::new((None, HashMap::new())))
}

/// Formats the headings of `WithHeadingRow` imports: `Maatwebsite\Excel\Imports\HeadingRowFormatter`.
///
/// Like PHP's static formatter, the registered formatters and the default apply to the whole
/// process.
pub struct HeadingRowFormatter;

impl HeadingRowFormatter {
    /// `FORMATTER_NONE`: headings stay as they are.
    pub const FORMATTER_NONE: &'static str = "none";
    /// `FORMATTER_SLUG`: headings become `Str::slug($heading, '_')`, such as `first_name`.
    pub const FORMATTER_SLUG: &'static str = "slug";

    /// Registers a formatter under `name`: `HeadingRowFormatter::extend()`. It receives each
    /// heading and its column index, and returns the row key.
    pub fn extend(name: impl Into<String>, formatter: impl Fn(&Value, usize) -> Key + Send + Sync + 'static) {
        formatters()
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .1
            .insert(name.into(), Arc::new(formatter));
    }

    /// Uses the formatter `name` instead of `excel.imports.heading_row.formatter`, or the
    /// configured one again with `None`: `HeadingRowFormatter::default()`.
    pub fn default(name: Option<&str>) -> Result<(), ExcelError> {
        let mut guard = formatters().write().unwrap_or_else(std::sync::PoisonError::into_inner);
        if let Some(name) = name
            && name != Self::FORMATTER_NONE
            && name != Self::FORMATTER_SLUG
            && !guard.1.contains_key(name)
        {
            return Err(ExcelError::UnknownFormatter(name.to_owned()));
        }
        guard.0 = name.map(str::to_owned);
        Ok(())
    }

    /// Uses the configured formatter again: `HeadingRowFormatter::reset()`.
    pub fn reset() {
        let _ = Self::default(None);
    }

    /// Formats a heading row: `HeadingRowFormatter::format()`.
    pub fn format(headings: &[Value]) -> Vec<Key> {
        let configured = crate::config::current().imports.heading_row_formatter;
        let guard = formatters().read().unwrap_or_else(std::sync::PoisonError::into_inner);
        let name = guard.0.clone().unwrap_or(configured);
        let custom = guard.1.get(&name).cloned();
        drop(guard);
        headings
            .iter()
            .enumerate()
            .map(|(index, value)| {
                if let Some(custom) = &custom {
                    return custom(value, index);
                }
                if value.is_empty() {
                    return Key::Index(index);
                }
                if name == Self::FORMATTER_SLUG {
                    return Key::from(slug(&value.to_text()));
                }
                Key::from(value.to_text())
            })
            .collect()
    }
}

/// `Str::slug($value, '_')`: transliterated to ASCII, lowercase, `@` as `at`, and every run of
/// other characters as one `_`.
pub fn slug(value: &str) -> String {
    use laravel::str::Str;

    let ascii = value.ascii();
    let mut title = String::with_capacity(ascii.len());
    let mut last_dash = false;
    for c in ascii.chars() {
        if c == '-' {
            if !last_dash {
                title.push('_');
            }
            last_dash = true;
        } else {
            last_dash = false;
            title.push(c);
        }
    }
    let title = title.replace('@', "_at_").to_lowercase();
    let kept: String = title
        .chars()
        .filter(|c| *c == '_' || c.is_alphanumeric() || c.is_whitespace())
        .collect();
    let mut out = String::with_capacity(kept.len());
    let mut in_separator = false;
    for c in kept.chars() {
        if c == '_' || c.is_whitespace() {
            if !in_separator {
                out.push('_');
            }
            in_separator = true;
        } else {
            in_separator = false;
            out.push(c);
        }
    }
    out.trim_matches('_').to_owned()
}

/// Whether reading needs rich text, links, images or number formats: the import, or one of its
/// sheets, formats data or has a column that needs them (`requiresStyleInformation()`).
pub(crate) fn requires_style_information(import: &dyn Import) -> bool {
    let concerns = import.__concerns();
    if concerns.format_data
        || concerns
            .columns
            .is_some_and(|columns| crate::columns::requires_style_information(&columns.columns()))
        || concerns
            .columns
            .is_some_and(|columns| columns.columns().iter().any(|column| column.formatted_by_default()))
    {
        return true;
    }
    match concerns.multiple_sheets {
        Some(multiple) => multiple
            .sheets()
            .imports()
            .iter()
            .any(|(_, sheet)| requires_style_information(sheet.as_ref())),
        None => false,
    }
}

// ---------------------------------------------------------------------------------------------
// Reading a sheet
// ---------------------------------------------------------------------------------------------

/// One sheet being imported, or one chunk of it: Laravel Excel's `Sheet` while importing.
pub struct SheetImport<'a> {
    pub(crate) sheet: &'a ReadSheet,
    pub(crate) start_row: u32,
    pub(crate) end_row: Option<u32>,
    pub(crate) chunk_offset: Option<u32>,
    pub(crate) middleware: &'a [CellMiddleware],
    pub(crate) listeners: &'a GlobalListeners,
    pub(crate) ignore_empty: bool,
}

struct RowReader<'c> {
    headings: Vec<Key>,
    grouped: Vec<bool>,
    end_column: Option<u32>,
    calculate: bool,
    format_data: bool,
    columns: Option<crate::columns::ColumnCollection>,
    progress: Option<&'c (dyn crate::concerns::WithProgressBar + Sync)>,
}

impl SheetImport<'_> {
    /// The sheet's highest row.
    pub fn highest_row(&self) -> u32 {
        self.sheet.highest_row()
    }

    /// The chunk's first row, for a `WithChunkReading` import.
    pub fn chunk_offset(&self) -> Option<u32> {
        self.chunk_offset
    }

    fn cell(&self, coordinate: Coordinate, calculate: bool) -> Value {
        self.cell_formatted(coordinate, calculate, false)
    }

    fn cell_formatted(&self, coordinate: Coordinate, calculate: bool, format_data: bool) -> Value {
        let value = if format_data {
            self.sheet.formatted(coordinate, calculate, None)
        } else {
            self.sheet.value(coordinate, calculate)
        };
        self.middleware
            .iter()
            .fold(value, |value, middleware| middleware.call(value))
    }

    fn reader<'c>(&self, concerns: &ImportConcerns<'c>) -> laravel::Result<RowReader<'c>> {
        let end_column = concerns.end_column()?;
        let calculate = concerns.calculated_formulas;
        let mut headings = Vec::new();
        if concerns.heading_row.is_some() {
            let number = concerns.heading_row_number();
            let last = end_column.unwrap_or_else(|| self.sheet.highest_column());
            let values: Vec<Value> = (1..=last)
                .map(|column| self.cell(Coordinate::new(column, number), false))
                .collect();
            headings = HeadingRowFormatter::format(&values);
        }
        let mut grouped = vec![false; headings.len()];
        if concerns.grouped_heading_row {
            for (index, heading) in headings.iter().enumerate() {
                grouped[index] = headings.iter().filter(|other| *other == heading).count() > 1;
            }
        }
        let columns = match concerns.columns {
            Some(with_columns) => {
                if concerns.mapped_cells.is_some() {
                    return Err(ExcelError::ColumnsAndMappedCells.into());
                }
                if concerns.column_limit.is_some() {
                    return Err(ExcelError::ColumnsAndColumnLimit.into());
                }
                if concerns.grouped_heading_row {
                    return Err(ExcelError::ColumnsAndGroupedHeadingRow.into());
                }
                let heading_row: Option<Vec<String>> = concerns
                    .heading_row
                    .is_some()
                    .then(|| headings.iter().map(ToString::to_string).collect());
                Some(crate::columns::ColumnCollection::make(
                    with_columns.columns(),
                    heading_row.as_deref(),
                    0,
                    concerns.format_data,
                    concerns.strict_null_comparison,
                )?)
            }
            None => None,
        };
        Ok(RowReader {
            headings,
            grouped,
            end_column,
            calculate,
            format_data: concerns.format_data,
            columns,
            progress: concerns.progress_bar,
        })
    }

    /// `Row::toArray()`: the row's values under their headings or positions.
    fn row(&self, reader: &RowReader<'_>, number: u32) -> Row {
        if let Some(progress) = reader.progress {
            progress.progress_advance(1);
        }
        if let Some(columns) = &reader.columns {
            return columns.read_row(self.sheet, number);
        }
        let last = reader.end_column.unwrap_or_else(|| self.sheet.highest_column());
        let mut row = Row::new();
        for column in 1..=last {
            let value = self.cell_formatted(Coordinate::new(column, number), reader.calculate, reader.format_data);
            let index = (column - 1) as usize;
            match reader.headings.get(index) {
                Some(heading) if reader.grouped[index] => match row.get(heading.clone()).cloned() {
                    Some(Value::Array(mut values)) => {
                        values.push(value);
                        row.insert(heading.clone(), Value::Array(values));
                    }
                    _ => {
                        row.insert(heading.clone(), Value::Array(vec![value]));
                    }
                },
                Some(heading) => {
                    row.insert(heading.clone(), value);
                }
                None => row.push(value),
            }
        }
        row.with_number(number)
    }

    /// The rows to read: from the start row to the limit, the chunk's end, or the last row.
    fn rows(&self, concerns: &ImportConcerns<'_>) -> std::ops::RangeInclusive<u32> {
        let highest = self.sheet.highest_row();
        let limit_end = concerns.end_row(concerns.start_row_number(), highest);
        let end = [Some(highest), limit_end, self.end_row]
            .into_iter()
            .flatten()
            .min()
            .unwrap_or(highest);
        self.start_row..=end
    }

    fn skip_blank(&self, row: &Row) -> bool {
        self.ignore_empty && row.is_blank()
    }
}

// ---------------------------------------------------------------------------------------------
// Validation: `RowValidator`
// ---------------------------------------------------------------------------------------------

/// Validates rows, keyed by their row numbers. Returns the row numbers to skip, or the
/// `ValidationException` to stop with.
async fn validate(rows: &[(u32, Row)], concerns: &ImportConcerns<'_>) -> laravel::Result<Vec<u32>> {
    let Some(validation) = concerns.validation else {
        return Ok(Vec::new());
    };
    let attributes = validation.custom_validation_attributes();
    let rules = attributes.iter().fold(validation.rules(), |rules, (name, label)| {
        rules.label(name.trim_start_matches("*."), label)
    });
    let mut failures = Vec::new();
    for (number, row) in rows {
        match rules.validate(&row.to_json()).await {
            Ok(()) => {}
            Err(ValidationError::Invalid(invalid)) => {
                for (attribute, messages) in invalid.errors() {
                    let attribute = attribute.strip_prefix("*.").unwrap_or(attribute);
                    let attribute = attributes
                        .iter()
                        .find(|(name, _)| name.trim_start_matches("*.") == attribute)
                        .map_or(attribute, |(_, label)| label.as_str());
                    failures.push(Failure::new(*number, attribute, messages.clone(), row.clone()));
                }
            }
            Err(ValidationError::Failed(error)) => return Err(error),
        }
    }
    if failures.is_empty() {
        return Ok(Vec::new());
    }
    match concerns.skips_on_failure {
        Some(skips) => {
            let mut skipped: Vec<u32> = failures.iter().map(Failure::row).collect();
            skipped.dedup();
            skips.on_failure(failures);
            Ok(skipped)
        }
        None => Err(ValidationException::new(failures).into()),
    }
}

fn handle_error(concerns: &ImportConcerns<'_>, error: laravel::Error) -> laravel::Result<()> {
    match concerns.skips_on_error {
        Some(skips) => {
            skips.on_error(error);
            Ok(())
        }
        None => Err(error),
    }
}

fn mapped_row(sheet: &SheetImport<'_>, concerns: &ImportConcerns<'_>) -> laravel::Result<Option<Row>> {
    let Some(mapped) = concerns.mapped_cells else {
        return Ok(None);
    };
    let mut row = Row::new();
    for (key, coordinate) in mapped.mapping() {
        let coordinate = Coordinate::parse(coordinate)?;
        row.insert(key, sheet.cell(coordinate, concerns.calculated_formulas));
    }
    Ok(Some(row))
}

/// `Sheet::toArray()` for an import: the rows, skipping empty ones, mapped and prepared.
async fn sheet_rows(sheet: &SheetImport<'_>, concerns: &ImportConcerns<'_>) -> laravel::Result<Vec<(u32, Row)>> {
    let reader = sheet.reader(concerns)?;
    let mut rows = Vec::new();
    if sheet.start_row > sheet.sheet.highest_row() {
        return Ok(rows);
    }
    for number in sheet.rows(concerns) {
        let mut row = sheet.row(&reader, number);
        if sheet.skip_blank(&row) {
            continue;
        }
        if let Some(skips) = concerns.skips_empty_rows
            && (row.is_blank() || skips.is_empty_when(&row))
        {
            continue;
        }
        if let Some(mapping) = &concerns.mapping {
            row = mapping(row)?.with_number(number);
        }
        if let Some(validation) = concerns.validation {
            row = validation.prepare_for_validation(row).with_number(number);
        }
        rows.push((number, row));
    }
    Ok(rows)
}

/// The rows of a sheet without an import's destinations: `Sheet::toArray()`.
pub(crate) async fn to_rows(sheet: &SheetImport<'_>, import: &dyn Import) -> laravel::Result<Vec<Row>> {
    let concerns = import.__concerns();
    Ok(sheet_rows(sheet, &concerns)
        .await?
        .into_iter()
        .map(|(_, row)| row)
        .collect())
}

async fn validated_rows(sheet: &SheetImport<'_>, concerns: &ImportConcerns<'_>) -> laravel::Result<Vec<Row>> {
    let rows = sheet_rows(sheet, concerns).await?;
    let skipped = validate(&rows, concerns).await?;
    Ok(rows
        .into_iter()
        .filter(|(number, _)| !skipped.contains(number))
        .map(|(_, row)| row)
        .collect())
}

// ---------------------------------------------------------------------------------------------
// The destinations that `import!` calls.
// ---------------------------------------------------------------------------------------------

/// The column names `WithUpserts` and `WithUpsertColumns` return, as model columns.
struct ColumnNames(Vec<&'static str>);

impl<M> Columns<M> for ColumnNames {
    fn names(self) -> Vec<&'static str> {
        self.0
    }
}

fn upsert_columns<M: Model>(concerns: &ImportConcerns<'_>, unique_by: &[&'static str]) -> Vec<&'static str> {
    if let Some(columns) = concerns.upsert_columns {
        return columns.upsert_columns();
    }
    let key = M::META.key.name();
    let created_at = M::META.created_at.as_ref().map(|stamp| stamp.name);
    M::META
        .columns
        .iter()
        .map(|field| field.name)
        .filter(|name| *name != key && Some(*name) != created_at && !unique_by.contains(name))
        .collect()
}

async fn persist<I>(import: &I, concerns: &ImportConcerns<'_>, rows: Vec<Row>, mass: bool) -> laravel::Result<()>
where
    I: ToModel + Sync,
{
    let location = Location::caller();
    if concerns.skip_duplicates && concerns.upserts.is_none() {
        for row in rows {
            let models: Vec<_> = import.model(row).into_iter().collect();
            for model in models {
                let create = <I::Model as Model>::Create::from(model.__into_row(location));
                match create.await {
                    Ok(_) => {}
                    Err(error) if laravel::db::is_unique_violation(&error) => {}
                    Err(error) => handle_error(concerns, error)?,
                }
            }
        }
        return Ok(());
    }
    if mass {
        let models: Vec<_> = rows.into_iter().flat_map(|row| import.model(row)).collect();
        if models.is_empty() {
            return Ok(());
        }
        let result = match concerns.upserts {
            Some(upserts) => {
                let unique_by = upserts.unique_by();
                let updates = upsert_columns::<I::Model>(concerns, &unique_by);
                laravel::model::__upsert(models, ColumnNames(unique_by), ColumnNames(updates)).await
            }
            None => laravel::model::__insert(models).await,
        };
        if let Err(error) = result {
            handle_error(concerns, error)?;
        }
        return Ok(());
    }
    for row in rows {
        let models: Vec<_> = import.model(row).into_iter().collect();
        for model in models {
            let result = match concerns.upserts {
                Some(upserts) => {
                    let unique_by = upserts.unique_by();
                    let updates = upsert_columns::<I::Model>(concerns, &unique_by);
                    laravel::model::__upsert([model], ColumnNames(unique_by), ColumnNames(updates))
                        .await
                        .map(|_| ())
                }
                None => {
                    let create = <I::Model as Model>::Create::from(model.__into_row(location));
                    create.await.map(|_| ())
                }
            };
            if let Err(error) = result {
                handle_error(concerns, error)?;
            }
        }
    }
    Ok(())
}

async fn flush<I>(
    import: &I,
    concerns: &ImportConcerns<'_>,
    sheet: &SheetImport<'_>,
    batch: Vec<(u32, Row)>,
    batch_size: usize,
    start_row: u32,
) -> laravel::Result<()>
where
    I: ToModel + Sync,
{
    let skipped = validate(&batch, concerns).await?;
    let rows = batch
        .into_iter()
        .filter(|(number, _)| !skipped.contains(number))
        .map(|(_, row)| row)
        .collect();
    persist(import, concerns, rows, batch_size > 1).await?;
    let event = AfterBatch { batch_size, start_row };
    for listener in &sheet.listeners.after_batch {
        listener(&mut event.clone())?;
    }
    if let Some(events) = concerns.events {
        events.after_batch(&event)?;
    }
    Ok(())
}

/// `ToModel`: `ModelImporter::import()`, or `MappedReader` with `WithMappedCells`.
#[doc(hidden)]
pub async fn handle_models<I>(import: &I, sheet: &SheetImport<'_>) -> laravel::Result<()>
where
    I: ToModel + Import + Sync,
{
    let concerns = import.__concerns();
    if let Some(row) = mapped_row(sheet, &concerns)? {
        return persist(import, &concerns, vec![row], false).await;
    }
    if sheet.start_row > sheet.sheet.highest_row() {
        return Ok(());
    }
    let reader = sheet.reader(&concerns)?;
    let batch_size = concerns.batch_inserts.map_or(1, |batch| batch.batch_size().max(1));

    let mut batch: Vec<(u32, Row)> = Vec::new();
    let mut read = 0u32;
    let mut batch_start = sheet.start_row;
    for number in sheet.rows(&concerns) {
        read += 1;
        let row = sheet.row(&reader, number);
        if sheet.skip_blank(&row) {
            continue;
        }
        if let Some(skips) = concerns.skips_empty_rows
            && (row.is_blank() || skips.is_empty_when(&row))
        {
            continue;
        }
        let mut row = row;
        if let Some(validation) = concerns.validation {
            row = validation.prepare_for_validation(row).with_number(number);
        }
        if let Some(mapping) = &concerns.mapping {
            row = mapping(row)?.with_number(number);
        }
        batch.push((number, row));
        if batch.len().is_multiple_of(batch_size) {
            flush(
                import,
                &concerns,
                sheet,
                std::mem::take(&mut batch),
                batch_size,
                batch_start,
            )
            .await?;
            batch_start += read;
            read = 0;
        }
    }
    if read > 0 {
        flush(import, &concerns, sheet, batch, batch_size, batch_start).await?;
    }
    Ok(())
}

/// `ToCollection`.
#[doc(hidden)]
pub async fn handle_collection<I>(import: &I, sheet: &SheetImport<'_>) -> laravel::Result<()>
where
    I: ToCollection + Import + Sync,
{
    let concerns = import.__concerns();
    let rows = match mapped_row(sheet, &concerns)? {
        Some(row) => vec![row],
        None => validated_rows(sheet, &concerns).await?,
    };
    drop(concerns);
    import.collection(rows).await
}

/// `ToArray`.
#[doc(hidden)]
pub async fn handle_array<I>(import: &I, sheet: &SheetImport<'_>) -> laravel::Result<()>
where
    I: ToArray + Import + Sync,
{
    let concerns = import.__concerns();
    let rows = match mapped_row(sheet, &concerns)? {
        Some(row) => vec![row],
        None => validated_rows(sheet, &concerns).await?,
    };
    drop(concerns);
    import.array(rows).await
}

/// `OnEachRow`.
#[doc(hidden)]
pub async fn handle_each_row<I>(import: &I, sheet: &SheetImport<'_>) -> laravel::Result<()>
where
    I: OnEachRow + Import + Sync,
{
    let concerns = import.__concerns();
    let reader = sheet.reader(&concerns)?;
    for number in sheet.rows(&concerns) {
        let mut row = sheet.row(&reader, number);
        if sheet.skip_blank(&row) {
            continue;
        }
        if let Some(validation) = concerns.validation {
            row = validation.prepare_for_validation(row).with_number(number);
        }
        if let Some(skips) = concerns.skips_empty_rows
            && (skips.is_empty_when(&row) || row.is_blank())
        {
            continue;
        }
        let result = if concerns.validation.is_some() {
            match validate(&[(number, row.clone())], &concerns).await {
                Ok(skipped) if skipped.is_empty() => import.on_row(row).await,
                Ok(_) => Ok(()),
                Err(error) => Err(error),
            }
        } else {
            import.on_row(row).await
        };
        if let Err(error) = result {
            handle_error(&concerns, error)?;
        }
    }
    Ok(())
}

/// Imports one sheet (or chunk): `Sheet::import()`.
pub(crate) async fn import_sheet(
    import: &dyn Import,
    sheet: &mut ReadSheet,
    window: SheetWindow,
    context: &ImportContext,
) -> laravel::Result<()> {
    {
        let concerns = import.__concerns();
        for listener in &context.listeners.before_sheet {
            listener(&mut BeforeSheet {
                sheet: &mut sheet.worksheet,
            })?;
        }
        if let Some(events) = concerns.events {
            events.before_sheet(&mut BeforeSheet {
                sheet: &mut sheet.worksheet,
            })?;
        }
        if let Some(progress) = concerns.progress_bar
            && concerns.chunk_reading.is_none()
        {
            progress.progress_start(u64::from(sheet.highest_row()));
        }
    }
    {
        let middleware = context.config.imports.cell_middleware.clone();
        let sheet_import = SheetImport {
            sheet,
            start_row: window.start_row,
            end_row: window.end_row,
            chunk_offset: window.chunk_offset,
            middleware: &middleware,
            listeners: &context.listeners,
            ignore_empty: context.config.imports.ignore_empty,
        };
        import.__handle(&sheet_import).await?;
    }
    let concerns = import.__concerns();
    for listener in &context.listeners.after_sheet {
        listener(&mut AfterSheet {
            sheet: &mut sheet.worksheet,
        })?;
    }
    if let Some(events) = concerns.events {
        events.after_sheet(&mut AfterSheet {
            sheet: &mut sheet.worksheet,
        })?;
    }
    if let Some(progress) = concerns.progress_bar
        && concerns.chunk_reading.is_none()
    {
        progress.progress_finish();
    }
    if let Some(offset) = window.chunk_offset {
        let event = AfterChunk { start_row: offset };
        for listener in &context.listeners.after_chunk {
            listener(&mut event.clone())?;
        }
        if let Some(events) = concerns.events {
            events.after_chunk(&event)?;
        }
    }
    Ok(())
}

/// Which rows of a sheet to import.
#[derive(Debug, Clone, Copy)]
pub(crate) struct SheetWindow {
    pub start_row: u32,
    pub end_row: Option<u32>,
    pub chunk_offset: Option<u32>,
}

/// What an import runs with.
#[derive(Clone)]
pub(crate) struct ImportContext {
    pub config: ExcelConfig,
    pub listeners: GlobalListeners,
}

impl ImportContext {
    pub(crate) async fn current() -> Self {
        Self {
            config: crate::config::current(),
            listeners: crate::excel::global_listeners().await,
        }
    }
}

/// Runs `work` in the configured transaction: `TransactionHandler`.
pub(crate) async fn transaction<T, F>(config: &ExcelConfig, work: F) -> laravel::Result<T>
where
    F: AsyncFnOnce() -> laravel::Result<T>,
{
    match config.transactions.handler.as_deref() {
        Some("db") => match &config.transactions.connection {
            Some(name) => laravel::db::connection(name)?.transaction(async |_| work().await).await,
            None => laravel::db::transaction(async |_| work().await).await,
        },
        _ => work().await,
    }
}

/// The sheets of a file paired with their imports: `Reader::loadSpreadsheet()` and `getSheet()`.
pub(crate) fn sheet_imports<'a>(
    import: &'a dyn Import,
    sheet_list: &[ReadSheet],
    owned: &'a [(SheetKey, Box<dyn Import>)],
) -> laravel::Result<Vec<(SheetKey, usize, &'a dyn Import)>> {
    let concerns = import.__concerns();
    if concerns.multiple_sheets.is_none() {
        return Ok((0..sheet_list.len())
            .map(|index| (SheetKey::Index(index), index, import))
            .collect());
    }
    let mut pairs = Vec::new();
    for (key, sheet_import) in owned {
        let found = match key {
            SheetKey::Index(index) => (*index < sheet_list.len()).then_some(*index),
            SheetKey::Name(name) => sheet_list.iter().position(|sheet| sheet.name() == name),
        };
        match found {
            Some(index) => pairs.push((key.clone(), index, sheet_import.as_ref())),
            None => {
                if let Some(skips) = concerns.skips_unknown_sheets {
                    skips.on_unknown_sheet(key);
                    continue;
                }
                if let Some(skips) = sheet_import.__concerns().skips_unknown_sheets {
                    skips.on_unknown_sheet(key);
                    continue;
                }
                return Err(match key {
                    SheetKey::Index(index) => ExcelError::SheetNotFoundByIndex {
                        index: *index,
                        count: sheet_list.len(),
                    },
                    SheetKey::Name(name) => ExcelError::SheetNotFoundByName(name.clone()),
                }
                .into());
            }
        }
    }
    Ok(pairs)
}

pub(crate) fn total_rows(sheets: &[ReadSheet]) -> BTreeMap<String, u32> {
    sheets
        .iter()
        .map(|sheet| (sheet.name().to_owned(), sheet.highest_row()))
        .collect()
}

pub(crate) fn before_import(
    import: &dyn Import,
    total_rows: &BTreeMap<String, u32>,
    listeners: &GlobalListeners,
) -> laravel::Result<()> {
    for listener in &listeners.before_import {
        listener(&mut BeforeImport { total_rows })?;
    }
    if let Some(events) = import.__concerns().events {
        events.before_import(&mut BeforeImport { total_rows })?;
    }
    Ok(())
}

pub(crate) fn after_import(
    import: &dyn Import,
    total_rows: &BTreeMap<String, u32>,
    listeners: &GlobalListeners,
) -> laravel::Result<()> {
    for listener in &listeners.after_import {
        listener(&mut AfterImport { total_rows })?;
    }
    if let Some(events) = import.__concerns().events {
        events.after_import(&mut AfterImport { total_rows })?;
    }
    Ok(())
}

pub(crate) fn import_failed(import: &dyn Import, error: &laravel::Error, listeners: &GlobalListeners) {
    for listener in &listeners.import_failed {
        listener(error);
    }
    if let Some(events) = import.__concerns().events {
        events.import_failed(error);
    }
}

/// The rows of each sheet, under the sheet's index or (with `WithMultipleSheets`) its key, as
/// `Excel::toArray()` returns them. Index it by position, as in `sheets[0]`.
pub type SheetRows = IndexMap<SheetKey, Vec<Row>>;

#[cfg(test)]
mod tests {
    use super::slug;

    #[test]
    fn headings_slug_like_laravel() {
        assert_eq!(slug("First Name"), "first_name");
        assert_eq!(slug("E-mail address"), "e_mail_address");
        assert_eq!(slug("Contact @ Work"), "contact_at_work");
        assert_eq!(slug("  Price (€)  "), "price_eur");
        assert_eq!(slug("Café"), "cafe");
    }
}